PythonString methods
str. format()
Inserts values into the places marked with curly braces.
- Returns
- A new, formatted string.
- Changes the original
- No
Example
#Python
template = "{name} scored {points:,} pts ({ratio:.0%} of goal)"
print(template.format(name="Emma", points=1240, ratio=0.62))
print("{} + {} = {}".format(2, 3, 2 + 3))
print("{0}{1}{0}".format("ab", "c"))Resultsaved result, you can check it
Emma scored 1,240 pts (62% of goal)
2 + 3 = 5
abcab
Definition and usage
#The format() method replaces {} fields in a string with successive arguments. Fields can be numbered ({0}) or named ({name}), and after a colon they take a format spec, just like in f-strings.
In new code, f-strings are usually more convenient. format() is still useful when the string template is stored separately, for example in a translation file, and filled in later.
The oldest formatting style, with the % operator ("%s is %d years old" % (name, age)), shows up in older code, but it is better to avoid it in new code.
Syntax
#Syntax
template.format(*args, **kwargs)Parameters
#args, kwargs
values
The values inserted into positional or named fields.
Good practices
#- Fill templates stored in translation files or configuration using
format(). - In regular code, prefer f-strings, they are shorter and clearer.
Related entries
#Spotted a mistake or missing an example? Write to us.