snippetpythonCritical
String formatting: % vs. .format vs. f-string literal
Viewed 0 times
literalstringformattingformat
Problem
There are various string formatting methods:
Which is better, and for what situations?
-
The following methods have the same outcome, so what is the difference?
-
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?.
- Python
- 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?.
Solution
To answer your first question...
yet, if
which is just ugly.
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
.format just 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:"Hello %s" % nameyet, if
name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do"Hello %s" % (name,) # supply the single argument as a single-item tuplewhich is just ugly.
.format doesn't have those issues. Also in the second example you gave, the .format example 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 to log.debug().Code Snippets
"Hello %s" % name"Hello %s" % (name,) # supply the single argument as a single-item tupleContext
Stack Overflow Q#5082452, score: 994
Revisions (0)
No revisions yet.