Have you mastered all three methods of Python format string,%s%d%f+format()+f-string, in-depth evaluation of YYDS is well deserved

πŸ“’πŸ“’πŸ“’πŸ“£πŸ“£πŸ“£
🌻🌻🌻 Hello, everyone. My name is Dream. I'm an interesting Python blogger. Please take care of me 😜😜😜
πŸ…πŸ…πŸ… CSDN 2021 blog star top 100, 2021 blog star top 5, high-quality creator in Python field, welcome to find me for cooperation and learning (VX wants to enter the learning exchange group or learning materials at the end of the article, welcome + + +)
πŸ’• Introduction note: this paradise is never short of genius, and hard work is your final admission ticket! πŸš€πŸš€πŸš€
πŸ’“ Finally, may we all shine where we can't see and make progress together 🍺🍺🍺
πŸ‰πŸ‰πŸ‰ "Ten thousand times sad, there will still be Dream, I have been waiting for you in the warmest place", which is me! Ha ha ha~ 🌈🌈🌈
🌟🌟🌟✨✨✨

In our daily study, we always have to deal with all kinds of input and output, among which output is the most important. Sometimes, because the output format is wrong or the grammar is incorrect, the final result is often unsatisfactory. As well as all kinds of wonderful output requirements, we often have a big head. Today, Dream will take you to actually evaluate and summarize various formatting string methods, and plant grass for your favorite methods as soon as possible~

1, % s%d%f method

In short, in python2 Before version 5, we used the most original formatting method% s, which is also the most commonly used method so far. It is simple and convenient. Let's take a look at his specific usage:

1. Symbolic symbols

When we see that there are% d,% s,% f and other percent signs in the output statement, this is the first% method we call.
Python supports string formatted output. Although this may encounter very complex expressions, the most basic usage is to insert a value into a string with string formatter% s.
Example 1: input:

name = 'yes Dream ah'
print('Hello,Hello, my name is%s'%name)

Output:

Hello,Hello, my name is Dream ah

Here, you should pay attention to that% should be used between the string and the variable instead of ','. Hello, everyone, my name is% s',name. If this connection is directly equivalent to outputting the variable after the string.
Example 2: input:

name = 'yes Dream ah'
print('Hello,Hello, my name is%s',name)

Output:

Hello,Hello, my name is%s yes Dream ah

2. Output data type

In the program, you can see an operator like% s, which is the symbol of string formatting in python. In addition, other types of data can be formatted with the% symbol. Common formatting symbols are as follows:

  • %s is formatted by str() string conversion
  • %f floating point real number
  • %d signed decimal integer

3.% 10s% - 10s%. 10s usage

(1)%10s

%10s means that the output width is 10 characters. If the output string does not exceed 10, fill in a space on the left; If the width exceeds 10, it shall be output according to the original length.
Example 3: input:

string = '12345'
print("123456789ABCDEFGHI")
print("%10s" %string) 

Output:

123456789ABCDEFGHI
     12345

(2)%-10s

Contrary to the above% 10s, if the width of the output string does not exceed 10, fill in the space on the right; If the width exceeds 10, it shall be output according to the original length.
Example 4: input:

string = '12345'
print("123456789ABCDEFGHI")
print("%-10s" %string + "aaaaa")  # If the length does not exceed 10, it shall be supplemented on the right
print("%-3s" %string + "aaaaa")  # If the length exceeds 3, output as is

Output:

123456789ABCDEFGHI
12345     aaaaa
12345aaaaa

(3)%.10s

%. 10s means to intercept the first 10 characters. If the original length is less than 10, it will be output as it is.
Example 5: input:

string = '12345'
print("123456789ABCDEFGHI")
print("%.3s" %string) #If the original length exceeds 3, intercept the first 3 characters
print("%.10s" %string)#If the original length is less than 10, output as is
123456789ABCDEFGHI
123
12345

(4)%10.3s

This format string should be divided into two parts. First run the ". 3" part on the right, that is, intercept three characters first; The function mentioned in "1" above is the function mentioned in "10". See the following examples for details:
Example 6: input:

string = '12345'
print("123456789ABCDEFGHI")
print("%10.3s" %string)      # Intercept 3 characters ("123") first. Since the length is less than 10, fill in 7 spaces on the left
print("%10.7s" %string)      # Intercept 7 characters ("12345") first. Since the length is less than 10, fill in 5 spaces on the left
print("%2.3s" %string)       # First intercept 3 characters ("123") and output as is because the length exceeds 2
123456789ABCDEFGHI
       123
     12345
123

4.% d% 2D% 02D% - 2D%%. 2D difference

%d is an ordinary output integer

%2d is to output the number with a width of 2 and right alignment. If the number of data bits is less than 2, fill in a space on the left.
%02d, similar to% 2d, but 0 is added on the left

%-2d output the number with width of 2 and left alignment. If the number of data bits is less than 2, fill in the space on the right
%At least 2 bits shall be output during. 2d output shaping. If it is not enough, the first bit shall be occupied by 0. If output 2 becomes 02200, only 200 is output; When outputting floating-point type (%. 2f), 2-digit output is forced after the decimal point
Example 7: input:

num = 1
print("%d" % (num))
print("%2d" % (num))
print("%02d" % (num))
print("%-2d" % (num))
print("%.2d" % (num))
print("%.2d" % (200))
1
 1
01
1 
01
200

5.%f detailed explanation

(1)%f

%f indicates the original value, and the default is 5 digits after the decimal point
Example 8: input:

import math
print('%f'%math.pi)
3.141593

(2)%9f

Only%9f, it means that the printing length is 9 digits, and the decimal point also accounts for one digit, which is not enough to fill in a space on the left
Example 9: input:

import math
print('%f'%math.pi)
print('%9f'%math.pi)
3.141593
 3.141593

(3)03.f

Only If there is no following number, it means that the decimal is removed and the integer is output. 03 means that there are not enough 3 digits and 0 is added to the left
Example 10: input:

import math
print('%f'%math.pi)
print('%.f'%math.pi)
print('%03.f'%math.pi)
3.141593
3
003

(4)%6.3f

%6.3f means that the decimal point is accurate to 3 digits, and the total length is 6 digits, including the decimal point. If it is not enough, fill in a space on the left
Example 11: input:

import math
print('%f'%math.pi)
print('%6.3f'%math.pi)
3.141593
 3.142

(5)%-6.3f

%-6.3f means that the decimal point is accurate to 3 digits, and the total length is 6 digits, including the decimal point. If it is not enough, fill in a space on the right
Example 12: input:

import math
print('%f'%math.pi)
print('%-6.3f'%math.pi)
3.141593
3.142     

2, format() method

From Python 3 Since the beginning of version 0 (python2.6 released at the same time), python supports the formatting of two versions at the same time. One new version is to use the format() function for formatted output.

1. No reference (1)

Example 13: input:

print('{} {}'.format('hello','world'))
hello world

2. No reference (2)

Example 14: input:

print('{0} {1}'.format('hello','world'))
world hello

3. No reference (3)

Example 15: input:

print('{1} {0} {1}'.format('hello','world'))
world hello world

4.key value

Example 16: input:

print('ID:{id},Name:{name}'.format(id='001',name='hello'))
ID:001,Name:hello

5. List

Example 17: input:

list=['001','hello']
print('ID:{List[0]},Name:{List[1]}'.format(List = list))
print('ID:{0[0]},Name:{0[1]}'.format(list))
ID:001,Name:hello
ID:001,Name:hello

6. Dictionary

Example 18: input:

dict={'id':'001,'name':'hello'}
print('ID:{Dict[0]},Name:{Dict[1]}'.format(Dict = dict))
print('ID:{id},Name:{name}'.format(**dict))
ID:001,Name:hello
ID:001,Name:hello

7. Category

Example 19: input:

class value():
	id = '001'
	name = 'hello'
print('ID:{Value.id},Name{Value.name}'.format(Value = value))
ID:001,Name:hello

8. Number formatting

  • 3.1415926 {:.2f} 3.14 two decimal places are reserved
  • 3.1415926 {:+.2f} +3.14 signed, with two decimal places reserved
  • -1 {:+.2f} -1.00 signed, with two decimal places reserved

9. Format summary

The first method: format and fill in a fixed form, and the order given is exactly the same as the filling order.
Example 20: input:

b1 = "Four Heavenly Kings:{},{},{},{}".format("yes Dream ah","Guo Fucheng","Xue You Zhang","dawn")
print(b1)
Four Heavenly Kings: Yes Dream Ah, Guo Fucheng, Zhang Xueyou, Liming

The second method: the subscript corresponding to the value passed in by format() is written in the braces {}.
Example 21: input:

b2 = "Four Heavenly Kings:{2},{0},{3},{1}".format("Lau Andy","Guo Fucheng","Xue You Zhang","dawn")
print(b2)

The third way: the variables in braces {} correspond to the value passed in by format().
Example 22: input:

x1 = "Lau Andy"
x2 = "Guo Fucheng"
x3 = "Xue You Zhang"
x4 = "dawn"
b3 = "Four Heavenly Kings:{p},{q},{r},{s}".format(p=x4,q=x2,r=x1,s=x3)
print(b3)

3, f-string method

python3. After version 6, a new string format, f-string, was introduced. From% s format to format format and then to f-string format, the format method is more and more intuitive. The efficiency of f-string is also higher than the first two, and it is simpler to use than the first two.
f-string format: placeholder {}, used with f symbol.

Simple use

f-string indicates the replaced field with curly braces {}, in which the replacement content is filled directly:
Example 23: input:

name = 'yes Dream ah'
print('Hello, my name is {name}'.format(name=name))
print(f'Hello, my name is {name}')
Hello, my name is yes Dream ah
Hello, my name is yes Dream ah

Example 24: input:

import datetime
name = 'yes Dream ah'
age = 20
date = datetime.date(2022,2,5)
print(f'my name is {name}, this year is {date:%Y},Next year, I\'m {age+1}')
# my name is Dream, this year is 2022,Next year, I'm 21

Other methods are also consistent with the format () function method. You can refer to them by yourself.

Summary planting grass

python's first method of formatting strings is%, but its fatal disadvantage is the limited types supported. format() is more comprehensive, while some f-strings in format() are basically available and simpler. Therefore, generally speaking, f-strings are used, except for format() under special circumstances.

πŸ† Previous articles -- good article recommendation πŸ†

πŸ₯‡ 2021 between me and CSDN -- from passers-by to a Wanfen blogger's Readme
πŸ₯ˆ [Python training camp] let's have a fun party!
πŸ₯‰ [Python open class] zero foundation playing with Python advanced chapter -- Section 1: file operation in Python
πŸ’•πŸ’•πŸ’• Well, that's all I want to share with you today. See you next time! ✨ ✨ ✨
🍻🍻🍻 If you like it, don't be stingy with your one button three connections~

Keywords: Python Back-end

Added by nathanr on Sat, 05 Feb 2022 09:19:26 +0200