Jun-09-2018, 12:45 PM
Please read the docs about strings... specially the format and the f-strings.
As a summary there are 4 methods to create strings with the value of a variable in it:
There are a few more (strings.Template) but with this 4 options you cover the 99% of the cases.
As a summary there are 4 methods to create strings with the value of a variable in it:
- Using str:
print("Your score was " + str(score) + " out of 5")
You have no control of the format used
- Using the old % syntax:
print("Your score was %d out of 5" % score) # Or, for more than 1 variable print("Your score was %d out of %d" % (score, 5))
You control the format and is easy for 1 or 2 variables...
- The format command:
print("Your score was {} out of 5".format(score)) # but can be something complex as: print("Your score was {:{w}d} out of {}".format(score, 5, w=3))
Much versatile than the %-formatting, more complex, also.
- f-strings, only for python3.6+
print(f"Your score was {score} out of 5") # Accept almost anything you can do with format w = 3 print(f"Your score was {score:{w}d} out of 5")
For me the cleanest option to format strings...
There are a few more (strings.Template) but with this 4 options you cover the 99% of the cases.