Search code examples
pythoncs50string-interpolation

Why is there a space in this string when printed?


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 :)


Solution

  • Your space you are forcing to be there is right here in your f-string:

    print(f"Hello, {name}")
         #        ^
         #        |
         # this adds the space
    

    The f-string (f"string" format string) says to print "Hello, " (with that space after the comma), followed by {name}, which is the variable name substituted 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:

    name = "David"
    print("Hello,", name)
    

    Output:

    Hello, David
    

    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:

    print("Hello,", name, sep="")
    

    ...or, with using the f-string, but leaving the space out, like this:

    print(f"Hello,{name}")
         #       ^
         #       |
         #   no space
    

    Both of those will output this:

    Hello,David
    

    Here is how the Python print() function works:

    I can see why you'd be confused. Take note of the following:

    1. This is 1 argument into the print function. Don't confuse the comma inside this string as being a comma that is separating multiple arguments into the print function:

      arg1 = the f-string f"Hello, {name}"

      print(f"Hello, {name}")
      
    2. This is 2 comma-separated arguments into the print function:

      arg1 = the string "Hello,"
      arg2 = the variable name

      print("Hello,", name)
      # Note: this is the same. The space between arguments makes no difference.
      # This just looks uglier is all:
      print("Hello,",name)
      
    3. This is 3 comma-separated arguments into the print function:

      arg1 = the string "Hello,"
      arg2 = the variable name
      arg3 = the dictionary keyword argument sep="", where sep is a predefined and recognized dictionary keyword according to the official documentation for the print() function.

      print("Hello,", name, sep="")