three methods
There are already many articles describing the three formatting methods of Python. Here are a few more detailed ones:
- Programmer's Inn: Python's 3 String Formatting, Make a Super Full Comparison!
- Tencent Cloud: Python string three formatted output
- CSDN: In-depth explanation of python string formatting (four methods)
The above is not the "eight ways of writing fennel". As a common tool for python programmers, it is necessary to make the most efficient choice in the appropriate scenario. Here is a brief summary:
Concise comparison
%format | format function | f-string | |
---|---|---|---|
order | Arguments must be in the exact order given | You can specify numerical order, or order by parameter name | Direct string encoding parameter name, no need for sequential correspondence |
feature | Closest to c language printf style | More flexible and more readable than % | Best readable and most flexible |
Version | Compatible with all versions | 2.6 appeared, 2.7 perfected | 3.6 |
% format
a = '小明同学'
b = '你出去'
print('%s,%s!' % (a, b))
format function
a = '小明同学'
b = '你出去'
print('{},{}!'.format(a, b))
f-string
a = '小明同学'
b = '你出去'
print(f'{a},{b}!')
The output of the above three of code are: 161f5729777788 Xiao Ming, you go out! , is it obvious that f-string is the most readable and the most concise code?
Choose a suggestion
- If the python version of the project is greater than 3.6 then obviously choose f-string
- If the python version is less than 3.6 but greater than 2.6, then the format function can be selected
- Only the version is lower than 2.6, or there is a lot of c code in the project, in order to keep the style consistent, it is suitable to choose the original % formatting style
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。