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
Release: 2024-12-18 14:45:24
Original
865 people have browsed it

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}"
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template