This Python String Formatting lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
f-strings are the current default. The expression inside braces is evaluated and inserted.
format still works and is useful when the template arrives as data. % formatting is older and easy to get wrong.
Example 1: Start here
An f-string cannot be an empty pair of quotes with a later substitution. The values are read where the string is written.
name = "Arun" # text
score = 74 # a whole number
print(f"{name} scored {score}") # the f before the quote fills in the braces
print("{0} scored {1}".format(name, score))
Example 2: An f-string
Put variables inside braces. The f before the quote turns them on.
name = "Asha" # text
score = 82 # a whole number
print(f"{name} scored {score}") # the f before the quote fills in the braces
Example 3: format method
Each pair of braces takes the next argument.
print("{} scored {}".format("Asha", 82)) # print writes this; the quotes are not shown
Example 4: A number format
.1f prints one digit after the decimal point.
score = 82 # a whole number
print(f"{score:.1f}") # the f before the quote fills in the braces
