Three ways to format output in Python: %, string.format(), f-string

Table of contents

1. % method

2. string.format() method

3. f-string method


Event address: CSDN 21-day learning challenge


1. % method

       Using % to format strings is a usage inherited from the C language. This method is relatively old and is not recommended . However, in the Python language, we will also see % formatted output. To figure out what the code means, let's look at its usage.

Usage format:  'format string' % (output item 1, output item 2,...output item n)     (Note: If there is only one output item, the last pair of brackets can be omitted)

Format string:

 flags: optional, available values ​​are:

Empty: right aligned

for - : left aligned

width: optional, the width of the output field

.precision: Optional, the number of digits left after the decimal point (note: if it is a string output, the number of digits left after the decimal point is intercepted)

 typecode: required, available values ​​are:

c: Output in character form, only one character is output

s: output string

d/i: Output integers in signed decimal form (positive numbers do not output signs)

f: Output single or double precision numbers in decimal form, implicitly outputting 6 decimal places

o : Output the integer in unsigned octal form

e/E: Output real numbers in exponential form

g/G: Select the format with shorter output width among %f or %e format, and do not output meaningless 0

x/X: Output the integer in hexadecimal unsigned form (without outputting the leading character 0x). When using

%: When there is a formatting mark in the string, %% needs to be used to represent a percent sign

Case number one:

Output:

n1=13, n2=14 

Case 2:

 

Output: 

521.131
               521.1
                         521.1
521.13              
521.13    

 

Case three:

 

Output:

I love the People's Republic of China
                            I love
I love  
   

 

2. string.format() method

Use string.format() to format strings. This is a new method and is officially recommended . Compared with the basic formatted output using the '%' method, format() is more powerful. This function treats the string as a template, formats it through the passed parameters, and uses curly brackets '{}' as special characters instead of ' %'

Use the format:  '{ }' .format(output item[, format string]) , where the format string is a selectable item.

There are 5 basic usages: 


1. Position replacement:

# 按照先后顺序对format内容进行替换
print('岗位:{}, 性别:{}'.format('经理', '男'))
# 输出: 
# 岗位:经理, 性别:男

2. Index replacement:

# 按照索引对format内容进行替换
print('岗位:{0}, 性别:{1}, 岗位:{0}'.format('经理', '男'))
# 输出: 
# 岗位:经理, 性别:男, 岗位:经理

 3. Keyword matching:

# 按照索引对format内容进行替换
print('岗位:{gw}, 性别:{xb}, 岗位:{gw}'.format(gw='经理', xb='男'))
# 输出: 
# 岗位:经理, 性别:男, 岗位:经理

4. Object replacement: 

# =======对象为元组==========#
tup1 = ("张三", "男")
tup2 = ('李四', '女')
print('名字:{0[0]}, 性别:{0[1]}; 名字:{1[0]}, 性别:{1[1]}'.format(tup1, tup2))
# 输出:
# '名字:张三, 性别:男; 名字:李四, 性别:女'

# =======对象为列表=======#
lis1=["张三","男"]
lis2=["李四","女"]
print('名字:{0[0]}, 性别:{0[1]}; 名字:{1[0]}, 性别:{1[1]}'.format(lis1, lis2))
# 输出:
# '名字:张三, 性别:男; 名字:李四, 性别:女'

# =========== 字典 ==========#
dic1 = {'姓名': '张三', '性别':'男'}
dic2 = {'姓名': '李四', '性别':'女'}
print('名字:{0[姓名]}, 性别:{0[性别]}; 名字:{1[姓名]}, 性别:{1[性别]}'.format(dic1, dic2))
# 输出:
# '名字:张三, 性别:男; 名字:李四, 性别:女'

5. Nested replacement 

print('hello {3:{1}>{2}} '.format('李四','*',10,'你好'))
# 输出: hello ********你好

print('hello {0:{1}^{2}} '.format('李四','*',10,'你好'))
# 输出: hello ****李四**** 

 

 Commonly used formatted output methods include the following 8 types:


1. Left alignment and padding 

#========== 左对齐 ==========#
print('%-5s'%'张三' )             # 常数5表示占5个字符,-:表示左对齐
# 输出:'张三    '
print('{:<5}'.format('张三'))    # 常数5表示占5个字符,<:表示左对齐
# 输出:'张三    '
print('{:*<5}'.format('张三') )  #  <表示左对齐, *表示用*号进行填充, 常数5表示占5个字符
# 输出:'张三***'

 2. Right alignment and padding

#========== 右对齐 ===========#
print('%5s'%'张三')               # 常数5表示占5个字符,默认右对齐
#输出:'   张三'
print('{:>5}'.format('张三') )    # 常数5表示占5个字符, >:表示右对齐
# 输出:'   张三'
print('{:*>5}'.format('张三'))    # 常数5表示占5个字符, >:表示右对齐, *表示用*号进行填充,
# 输出:'***张三'

 3. Center alignment and filling

#========== 居中对齐 ===========#
print('{:^5}'.format('张三'))
# 输出:' 张三  '
print('{:*^5}'.format('张三') )   #  常数5表示占5个字符, >: 表示右对齐, *表示用*号进行填充,
# 输出:'*张三**'

4. Intercept a string of specified length 

#===== 截取指定长度字符串 =====#
print('%.2s'%'张三李四')  # 表示从字符串中截取两个字符
# 输出:'张三'

5. Percent sign 

#===== 百分号-% =====#
print('{:%}'.format(0.2))     # 默认输出保留6位小数
# 输出:'20.000000%'
print("{:.2%}".format(0.02))  # 百分比计算 常用
# 输出:'2.00%'

6. Comma separator 

# ===== 逗号分隔符 =====%
print('{:,}'.format(1232434234234))
# 输出:'1,232,434,234,234'

7. Time formatted output 

# ======== 对时间格式化输出 ========= #
import datetime
d = datetime.datetime(2022, 4, 29, 9, 52, 20)
print('{:%Y-%m-%d %H:%M:%S}'.format(d))
# 输出: '2022-04-29 09:52:20'

 

format conversion


b - binary. Output the number in base 2.

c - character. Convert integers to corresponding Unicode strings before printing.

d - Decimal integer. Output the number in base 10.

o - octal. Output the number in base 8.

x - hexadecimal. Output the numbers in base 16, and use lowercase letters for digits above 9.

e - Power symbol. Print numbers in scientific notation. Use 'e' to indicate exponentiation.

g - General format. Output the value in fixed-point format. When the value is particularly large, it is printed in power form.

n - number. Same as 'd' when the value is an integer, and the same as 'g' when the value is a floating point number. The difference is that it inserts number separators according to the locale.

% - Percentage. Multiply the value by 100 and print it in fixed-point('f') format, with a percent sign after the value.

#  ======== 格式转换 =========  #
print('{0:b}'.format(3))
# 输出:11
print('{:c}'.format(20))
# 输出:
print('{:d}'.format(20))
# 输出:20
print('{:o}'.format(20))
# 输出:24
print('{:x}'.format(20))
# 输出:14
print('{:e}'.format(20))
# 输出:2.000000e+01
print('{:g}'.format(20.1))
# 输出:20.1
print('{:f}'.format(20))
# 输出:20.000000
print('{:n}'.format(20))
# 输出:20
print('{:%}'.format(20))
# 输出:2000.000000%

3. f-string method

        Use f-string to format strings. This method is recommended in Python 3.6 and above . Python3.6 introduces a new string formatting method: f-string formatted string. From %s formatting to format formatting and then to f-string formatting, the formatting method is becoming 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. At the same time, it is worth noting that f-string has made some changes based on format formatting. The core usage idea is the same as format.

1. Basic use, f-string uses braces { } to represent the replaced field, and you can directly fill in the replacement content.

name = "Huang Wei"
print(f"Hello, my name is {name}")
# 输出:Hello, my name is Huang Wei

num = 2
print(f"I have {num} apples")
# 输出:I have 2 apples

price = 95.5
print(f"He has {price}$")
# 输出:He has 95.5$

 2. Expression evaluation and function calling. The curly braces { } of f-string can be filled in with an expression or a function called. Python will calculate the result and fill it in the returned string.

print(f"They have {2+5*2} apples")
# 输出:They have 12 apples

name = "Huang Wei"
print(f"my name is {name.lower()}")
# 输出:my name is huang wei

import math
print(f"Π的值为{math.pi}")
# 输出:Π的值为3.141592653589793

3. There are problems with the use of quotation marks in f-string. The quotation marks used within the curly braces of f-string cannot conflict with the quotation mark delimiter quotation marks outside the curly braces. Single quotation marks, double quotation marks, single triple quotation marks, etc. need to be flexibly switched according to the situation. Double triple quotes.

Note: As long as the quotes inside and outside the braces are different, there is no problem. However, only quotation marks and double quotation marks can be used inside the curly braces. The quotation mark delimiter quotation marks outside the curly braces can be single quotation marks, double quotation marks, single triple quotation marks, or double triple quotation marks.

print(f'I am {"Huang Wei"}')
# 输出:I am Huang Wei

print(f'''I am {'Huang Wei'}''')
# 输出:I am Huang Wei

print(f"""I am {'Huang Wei'}""")
# 输出:I am Huang Wei

print(f"""I am {"Huang Wei"}""")
# 输出:I am Huang Wei

print(f'I am {'Huang Wei'}')
# 输出:
#     print(f'I am {'Huang Wei'}')
#                    ^^^^^
# SyntaxError: f-string: expecting '}'

4. Quotation marks outside curly braces can also be escaped with \, but \escaping cannot be used within curly braces.

print(f"he\'ll go to {'shang hai'}")
# 输出:he'll go to shang hai

print(f"""he introduces himself {"I\'m Tom"}""")
#输出:
#     print(f"""he introduces himself {"I\'m Tom"}""")
#                                                    ^
# SyntaxError: f-string expression part cannot include a backslash

print(f"""he introduces himself {"I'm Tom"}""")
# 输出:he introduces himself I'm Tom

 5. If you need to display braces outside the f-string braces, you should enter two consecutive braces { { }}; if you need quotation marks inside the braces, just use them.

print(f"5{'{apples}'}")
#输出:5{apples}

print(f"{
   
   {5}}{'apples'}")
#输出:{5}apples

6. f-string filling

When we specify the final length of the string, if the existing string is not that long, then we use some kind of character (filling character) to fill the length, which is "padding".

6.1 Use spaces to fill by default

name = "Huang Wei"
print(f"{name:>20}")
#输出:           Huang Wei

print(f"{name:<20}")
#输出:Huang Wei

print(f"{name:^20}")
#输出:     Huang Wei

6.2 Fill with specified characters

name = "Huang Wei"
print(f"{name:_>20}")
#输出:___________Huang Wei

print(f"{name:_<20}")
#输出:Huang Wei___________

print(f"{name:_^20}")
#输出:_____Huang Wei______

Note: Filling is divided into left filling, right filling and center filling. Left padding means padding on the left side of the string, right padding means padding on the right side of the string, and center padding means filling symmetrically on the left and right sides of the string. > means left padding, < means right padding, and ^ means center padding. Memory method: If the brackets are facing to the left, it means left padding; if the brackets are facing to the right, it means right padding.

7. The combination of f-string truncation and padding, truncation will only occur when the data type to be formatted is "string".

# 当发生截断的时候,如果不指定填充符,默认使用空格填充
print(f"{a:10.3}")
#输出:Hel
# 在发生截断的时候,使用指定的填充符
print(f"{a:_>10.3}")
#输出:_______Hel
print(f"{a:_<10.3}")
#输出:Hel_______

 8. F-string extracts information such as year, month, day, hour, minute, and second for date, datetime, and time objects.

from datetime import *
# today()返回本地时间的一个date对象
a = date.today()
print(f"{a:%Y-%m-%d}")
#输出:2020-02-01

 

Guess you like

Origin blog.csdn.net/weixin_44793743/article/details/126319206