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

Question:

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:' + ' Johnn'
    surname = 'Surname: ' + 'Doen'
    age = 'Age : '+ str(20) + ("n")
    wasHere = 'Was here before?: ' + 'Yesn'
    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:

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.

Asked By: NotoriCode

||

Answers:

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
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.