头图

three methods

There are already many articles describing the three formatting methods of Python. Here are a few more detailed ones:

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

%formatformat functionf-string
orderArguments must be in the exact order givenYou can specify numerical order, or order by parameter nameDirect string encoding parameter name, no need for sequential correspondence
featureClosest to c language printf styleMore flexible and more readable than %Best readable and most flexible
VersionCompatible with all versions2.6 appeared, 2.7 perfected3.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

  1. If the python version of the project is greater than 3.6 then obviously choose f-string
  2. If the python version is less than 3.6 but greater than 2.6, then the format function can be selected
  3. 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

songofhawk
303 声望24 粉丝