Search code examples
python-3.xstringformattingstring-formattingoperator-keyword

Why do programmers use %s in the print statement, instead of adding the variable, which holds a specific value(string), to the print statement?


I don't understand why programmers use %s, when they can simply just add the variable name to the print statement. I mean its less work to type in the variable name instead of " ...%s" % name) "

Example:

# declaring a string variable
name = "David"
 
# append a string within a string
print("Hey, %s!" % name)`

Why do Programmers not type in instead:

# declaring a string variable
name = "David"

# printing a salutation without having to append a string within a string:
print("Hey," + " " + name + "!")`
```


Solution

  • There may be some performance difference, but it mostly comes down to preference.

    The most modern approach is to use f-strings. With your example this would look like this:

    # declaring a string variable
    name = "David"
    
    # format print using f-string
    print(f"Hey, {name}!")
    

    This way there is no %s not is there need for all the extra + symbols and spaces.

    Good Luck!