String formatting
String formatting is a common and important operation to dynamically generate strings containing variable content. Regarding the formatting of strings, there have been many ways to format strings in the history of Python, so this may cause trouble. Some people may not know which formatting method should be used. Let me introduce it in detail below.
Current recommended practice: f-string
There is no doubt that f-string is the most suitable method for string formatting now, so first of all, it is introduced. f-string was first introduced since 3.6, so it requires python versions after 3.6 to be used.
How to use: Add f or F before the string, and fill in the curly braces {} with variables or expressions.
name = "sagegrass" age = 18 greeting = f"Hello,My name is{name},I'm this year{age}age,I last year{age - 1}age" print(greeting)
After python 3.8, f-string debugging support was added, using the method to add = after variables or expressions, so as to output the name and result at the same time.
name = "sagegrass" print(f"{name=}") # At this time the output result is name=sagegrass
Historical practices
%format
Historical practices are very common in previous versions of python, which you can see in a lot of earlier codes, and, to this day, are not completely useless, and some people may still do this now (but it is better to use f-string instead).
% formatting is the earliest string formatting method in Python. It has a history of decades and was first inherited from the C language.
How to use: "Format String" % Value
name = "sagegrass" age = 18 greeting = "Hello, my name is %s, I am %d this year, I am %d last year" % (name, age, age - 1) print(greeting)
Among them, %s is used for strings, %d is used for integers, and another commonly used is %f, which is used for formatting of floating point numbers. However, because it is relatively old, it is not easy to use and is prone to problems, it is no longer recommended to use it now.
format format
format format was introduced during the Python 2.6 and 3.0 period. format provides more powerful and flexible string formatting functions.
How to use: "Format String".format(value 1, value 2, ...)
p1 = "Hoing" p2 = "At noon" p3 = "Sweat Drop" p4 = "Getting down the soil" poem = "{}day{},{}millet{}".format(p1, p2, p3, p4) print(poem)
format format also allows for positional parameters to be provided, using the same variable multiple times.
p1 = "One Inch" p2 = "time" p3 = "gold" poem = "{0}{1}{0}{2},inch{2}难买inch{1}".format(p1, p2, p3) print(poem)
format format also allows for the provision of keyword parameters, used according to the specified parameter name.
name = "sagegrass" age = 18 greeting = "Hello,My name is{name},I'm this year{age}age,I last year{age_of_last_year}age".format(name=name, age=age, age_of_last_year=age - 1) print(greeting)
Unlike % formatting strings, format is still a very good choice. Even in some languages, the latest way to format strings is a similar way to format.
Template format string
This is a good way to format strings, but it is less used, which may have something to do with it coming from the string module and not being used directly.
from string import Template name = "sagegrass" age = 18 template = Template("Hello, my name is $name, I am $age this year, I am $age_of_last_year last year") greeting = (name=name, age=age, age_of_last_year=age - 1) print(greeting)
If safe_substitute is used, then no exception will be thrown when the variable is missing, and the original text will be retained at this time.
from string import Template name = "sagegrass" age = 18 template = Template("Hello, my name is $name, I am $age this year, I am $age_of_last_year last year") greeting = template.safe_substitute(name=name) print(greeting) # Hello, my name is sagegrass, I am $age this year, I am $age_of_last_year last year
Not commonly used
String stitching
There are also some practices that are not very good. If it is not a special case, it should not be used as a string formatting method. The following is a brief introduction, but you should be careful in actual use.
String splicing is to splice multiple strings into one through the + operator, for example. It can indeed generate strings dynamically, but it is not actually a way to format strings.
name = "sagegrass" age = 18 greeting = "Hello, my name is" + name + ", I'm this year" + str(age) +"Year, I last year" + str(age - 1) + "age" print(greeting)
This method is indeed simple and easy to understand, but the disadvantage is that it is low performance and difficult to understand (especially when the number of spliced strings increases)
()connect
join() is not actually used for string formatting, it is usually used for some other functions. It plays a similar function to string splicing, but its performance is usually better. It is theoretically a superior replacement for string splicing, but it is still not recommended.
name = "sagegrass" age = 18 greeting = "".join(("Hello, my name is", name, ", I'm this year", str(age), "Year, I last year", str(age - 1), "age")) print(greeting)
Custom string formatting
This is possible only with very special needs, and in general, this is actually quite strange.
import re def my_format(template, **kwargs): return (r'\{(\w+)\}', lambda match: str(((1), (0))), template) name = "sagegrass" age = 18 greeting = my_format("Hello,My name is{name},I'm this year{age}age,I last year{age_of_last_year}age", name=name, age=age, age_of_last_year=age - 1) print(greeting)
The disadvantages include some errors in customization, or performance issues, and the advantage is that you can customize the method of formatting strings according to your own ideas and add some additional features you need.
Summarize
2024 is almost over, and 2025 will be in a few months. For new code, f-string should be used as much as possible (as of python3.12). This may have been a problem in the past, because in the past few years, there may have been a lot of people using python3.5. This version does not have the f-string function, but today, 3.7 is already very rare, and the use of f-string is no longer a "version" problem.
The above is the detailed summary of the method of formatting strings in Python. For more information about formatting strings in Python, please pay attention to my other related articles!