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?.
To answer your first question...
.formatjust seems more sophisticated in many ways. An annoying thing about%is also how it can either take a variable or a tuple. You'd think the following would always work:yet, if
namehappens to be(1, 2, 3), it will throw aTypeError. To guarantee that it always prints, you'd need to dowhich is just ugly.
.formatdoesn't have those issues. Also in the second example you gave, the.formatexample is much cleaner looking.Only use it for backwards compatibility with Python 2.5.
To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression
log.debug("some debug info: %s" % some_info)will first evaluate the string to, e.g."some debug info: roflcopters are active", then that string will be passed tolog.debug().