Home >Backend Development >Python Tutorial >Python String Formatting: % vs. .format vs. f-strings - Which Method Should You Choose?
String Formatting: % vs. .format vs. f-String Literals
Question:
There are multiple methods for formatting strings in Python: % formatting, .format method, and f-strings. Which is preferable and under what circumstances?
Answer:
Comparison of Formatting Methods
The following code demonstrates the equivalent outcomes of different formatting methods:
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}"
While all methods produce the same output, .format offers advantages over % formatting. For instance, % formatting requires tuples for multiple arguments, which is cumbersome. .format also supports named arguments, which enhances readability.
Runtime Performance
String formatting takes place during expression evaluation. For example, in the expression log.debug("some debug info: %s" % some_info), the string is evaluated and passed to log.debug().
To avoid runtime performance penalties, it's recommended to avoid string formatting in critical sections. Consider using logger.
The above is the detailed content of Python String Formatting: % vs. .format vs. f-strings - Which Method Should You Choose?. For more information, please follow other related articles on the PHP Chinese website!