python中format()方法的使用


在Python3中,字符串格式化操作通过format()方法,format()方法拥有更多的功能,操作起来更加方便。该函数将字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号{}作为特殊字符代替%

位置设定

不指定位置的时候,使用默认位置

不指定格式化位置,按照默认顺序格式化

S = 'I {} {}, and I\'am learning'.format('like', 'Python') print(S) 

示例结果:

I like Python, and I'am learning 

设置位置

设置数字顺序指定格式化的位置

S = 'I {0} {1}, and I\'am learning'.format('like', 'Python') print(S) # 打乱顺序 S = 'I {1} {0} {1}, and I\'am learning'.format('like', 'Python') print(S) 

示例结果:

I like Python, and I'am learning I Python like Python, and I'am learning 

设置关键字

设置关键字指定格式化的内容

S = 'I {l} {p}, and I\'am learning'.format(p='Python', l='like') print(S) S = 'I {p} {l}, and I\'am learning'.format(p='Python', l='like') print(S) 

示例结果:

I like Python, and I'am learning I Python like, and I'am learning 

参数传递

我们可以传入各种类型参数格式化字符串,即不限于字符串变量或数字等。

元组传参

利用元组传参,传参形式 *tuple

# 定义一个元组 T = 'like', 'Python' # 不指定顺序 S = 'I {} {}, and I\'am learning'.format(*T) print(S) # 指定顺序 S = 'I {0} {1}, and I\'am learning'.format(*T) print(S) 

示例结果:

I like Python, and I'am learning I like Python, and I'am learning 

字典传参

# 定义一个字典 D = {'l':'like', 'p':'Python'} # 指定键确定顺序 S = 'I {l} {p}, and I\'am learning'.format(**D) print(S) 

示例结果:

I like Python, and I'am learning 

列表传参

# 定义一个列表 L0 = ['like', 'Python'] L1 = [' ', 'Lerning'] # `[]`前的0、1用于指定传入的列表顺序 S = 'I {0[0]} {1[1]}, and I\'am learning'.format(L0, L1) print(S) 

示例结果:

I like Lerning, and I'am learning

格式限定符

format通过丰富的的“格式限定符”(语法是 {}中带:号)对需要格式的内容完成更加详细的制定。

进制转换

我们可以再限定符中制定不同的字符对数字进行进制转换的格式化,进制对应的表格:

字符 含义
b 二进制
c Unicode 字符
d 十进制整数
o 八进制数
x 十六进制数,a 到 f 小写
X 十六进制数,A 到 F 大写
N = 99 print('{:b}'.format(N)) print('{:c}'.format(N)) print('{:d}'.format(N)) print('{:o}'.format(N)) print('{:x}'.format(N)) print('{:X}'.format(N)) 

示例结果:

1100011 c 99 143 63 63 

填充与对齐

:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充,且填充常跟对齐一起使用,^<>分别是居中、左对齐、右对齐,后面带宽度。

N = 99 print('{:>8}'.format(N)) print('{:->8}'.format(N)) print('{:-<8}'.format(N)) print('{:-^8}'.format(N)) 

示例结果:叉车租赁

      99 ------99 99------ ---99--- 

精度

:号后面设置精度(以.开始加上精度),然后用f结束,若不是设置,默认为精度为6,自动四舍五入,可带符号显示数字正负标志。

N = 99.1234567 NN = -99.1234567 print('{:f}'.format(N)) print('{:.2f}'.format(N)) print('{:+.2f}'.format(N)) print('{:+.2f}'.format(NN)) 

示例结果:

99.123457 99.12 +99.12 -99.12 

转义

我们可以使用大括号 {} 来转义大括号。

p = 'Python' S = 'I like {}, and {{0}}'.format(p) print(S) 

示例结果:

I like Python, and {0}
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM