Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python print statement adds spaces between arguments

Tags:

python

spacing

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!")
like image 547
Shawna F Avatar asked Dec 18 '25 15:12

Shawna F


1 Answers

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

like image 164
HPringles Avatar answered Dec 20 '25 08:12

HPringles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!