There are various string formatting methods:
- Python <2.6:
"Hello %s" % name
- Python 2.6+:
"Hello {}".format(name)
(usesstr.format
) - Python 3.6+:
f"{name}"
(uses f-strings)
Which is better, and for what situations?
The following methods have the same outcome, so what is the difference?
name = "Alice" "Hello %s" % name "Hello {0}".format(name) f"Hello {name}" # Using named arguments: "Hello %(kwarg)s" % {'kwarg': name} "Hello {kwarg}".format(kwarg=name) f"Hello {name}"
When does string formatting run, and how do I avoid a runtime performance penalty?
If you are trying to close a duplicate question that is just looking for a way to format a string, please use How do I put a variable’s value inside a string?.