Python print statement adds spaces between arguments

Viewed 586

I am coding a very basic hello program but I keep getting a space between the name and first exclamation mark that I am not seeing in the code. I have tried reformatting the string section a few different ways to concatenate the spacing out but I can't figure out what is causing the extra space. I've tried doing the exclamation mark alone, or part of the first of the next sentence, but it always has the extra space after the variable 'name'.

In contrast, the exclamation after variable age does not have the extra space, which is how I want both of them to look.

Here's the code and a screen shot - thanks you in advance.

name = input('Please enter your name: ')
age = input('Please enter your age: ')

print("Hello",name,"! You are",age,"nice to meet you!")
4 Answers

You can use f-strings. That is better and more pythonic:

print(f"Hello {name}! You are {age}. Nice to meet you!")

The , adds a space in python by default.

The python print function automatically adds a space between arguments. You should concatenate (join) the strings together and then print them

print("a","b") # a b
print("a" + "b") # ab

In python, you can use "f-strings" which are a way to "template" the string. text inside of {} is treated like python, so you can put variables in there.

print(f"Hello {name}! You are {age} nice to meet you!")

f-strings are the best approach in python, but the first solution with "+" will work just fine for this use-case

also you can use .format like this:

name = input('Please enter your name: ')
age = input('Please enter your age: ')

print("Hello {}! You are {} nice to meet you!".format(name , age))

or:

name = input('Please enter your name: ')
age = input('Please enter your age: ')

print("Hello {0}! You are {1} nice to meet you!".format(name , age))

second solution will be useful in cases like this:

print("{0} is software engineer. also his son want to be programmer. {0} is good trainer".format("jackob"))

and how it works?
every thing in .format(...) have an index! for example, in .format("jackob" , "sara"), "jackob" index is 0 and "sara" index is 1!

Use the print() statement with C-style flags. It gives you precise control over how your string comes out.

print('Hello %s! You are %d. Nice to meet you!' % (name, age))
Related