There is a space after Hello,, and I don't understand why.
This code from CS50'S Python course and I didn't get how its output is Hello,(space)David, for example, when the input name is David.
name = input("What is your name? ")
name = name.strip()
print(f"Hello, {name}")
How is there a space?
p.s. I guess that's so beginner question but I'm a beginner, so :)
Your space you are forcing to be there is right here in your f-string:
The f-string (
f"string"format string) says to print"Hello, "(with that space after the comma), followed by{name}, which is the variablenamesubstituted directly into the f-string at that location. Notice that the double quotes ("") are around the entire thing. Contrast this to the other examples below.If you wrote this instead, without the format string, it would still have a space simply because Python automatically adds spaces between printed arguments:
Output:
To force there to be no space, you'd have to force the separator to be an empty string by setting
sep=""without using the f-string, like this:...or, with using the f-string, but leaving the space out, like this:
Both of those will output this:
Here is how the Python
print()function works:I can see why you'd be confused. Take note of the following:
This is 1 argument into the
printfunction. Don't confuse the comma inside this string as being a comma that is separating multiple arguments into theprintfunction:arg1 = the f-string
f"Hello, {name}"This is 2 comma-separated arguments into the
printfunction:arg1 = the string
"Hello,"arg2 = the variable
nameThis is 3 comma-separated arguments into the
printfunction:arg1 = the string
"Hello,"arg2 = the variable
namearg3 = the dictionary keyword argument
sep="", wheresepis a predefined and recognized dictionary keyword according to the official documentation for theprint()function.