Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the first string variable from my function being printed out of line?

I’m just a newbie in python and programming in general. And i made this simple hospital python script which prints out a specific patient’s information. The code works just fine. But for some reason the final output gives me some weird spacing on the first string variable in comparision with the others, and i would like to understand why.. The code looks like this:

#Random generic newbie variable to activate the function later on

foo = True

#Function for printing information about a patient into the terminal.

def Patient1():
    name = 'Name:' + ' John\n'
    surname = 'Surname: ' + 'Doe\n'
    age = 'Age : '+ str(20) + ("\n")
    wasHere = 'Was here before?: ' + 'Yes\n'
    print (name, surname, age, WasHere)


if foo == True:
    Patient1()

The output i was expecting was something like this:

 Name: John
 Surname: Doe
 Age : 20
 Was here before?: Yes

But instead, it gave me this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name: John
 Surname: Doe
 Age : 20
 Was here before?: Yes

I do know i can fix this by simply putting a space before the first name string, but i’m really just curious as to why python is doing this.. I’m currently running this script in Powershell, i will later try and run it in bash aswell but i’m pretty sure this isn’t a Windows-specific kind of issue. Any help or tips would be gladly appreciated as i’m really only posting this for learning purposes.

>Solution :

When you call print with multiple arguments it defaults to putting spaces between them. Since the individual args end in newlines, the separating spaces end up at the start of each line after the first. The separator can be changed via the sep argument to print.

Try:

print(name, surname, age, WasHere, sep='')  # no separators between args

or:

print(name + surname + age + WasHere)  # only one arg, hence no separators

or you could remove the newlines from the actual strings and make them part of the print call, so that the formatting is more separated from the data:

print(name, surname, age, WasHere, sep='\n')  # linebreak as separator
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading