Home >Backend Development >Python Tutorial >Python String Formatting: % vs. .format vs. f-strings - Which Method Should You Choose?

Python String Formatting: % vs. .format vs. f-strings - Which Method Should You Choose?

DDD
DDDOriginal
2024-12-18 14:45:24862browse

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.("%s", str(some_info)) instead, which postpones string evaluation until after the logging level decision is made.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn