网络编程
位置:首页>> 网络编程>> Python编程>> Python format函数详谈

Python format函数详谈

作者:我是NeroZhang  发布时间:2023-12-24 03:57:59 

标签:Python,format,函数

Python字符串的format函数

format()函数用来收集其后的位置参数和关键字段参数,并用他们的值填充字符串中的占位符。通常格式如下:

'{pos or key : fill, align, sign, 0, width, .precision, type}'.format(para1...)

整个花括号是一个占位符,冒号前的位置或者关键字用来定位format函数的参数,冒号后面用来将该参数格式化,其中每一个都是可选项。

1.fill用来指定填充字符,默认为空格

2.align指定对齐方式:>为右对齐,<为左对齐,^为居中对齐

3.sign指定是否保留正负号:+为保留正负号,-为仅保留负号

4.宽度前面如果加0则表示用0填充

5.width指定宽度

6.precision指定精确度

7.type指定类型,如b为二进制,x为十六进制

一些示例如下:


#使用位置进行填充
print(
   'Hello,{0}. My name is {1}. How\'s it going?'.format('Hialry','Vergil')
   #Hello,Hialry. My name is Vergil. How's it going?
)
#若格式中未指定填充位置,将会按序填充
print(
   '{}--{}--{}--{}--{}--{}--{}'.format(1,2,3,4,5,6,7)
   #1--2--3--4--5--6--7
)

#使用关键字段进行填充
print(
   'I\'m {name1}, and I miss u so much, {name2}.'.format(name1='vergil',name2='hilary')
   #I'm vergil, and I miss u so much, hilary.
)

#使用下标填充
names=['hilary','vergil','nero']
places=['chengdu','shijiazhuang','tokyo']
print(
   'Hi, {names[0]}. I am {names[1]} and this is {names[2]}.'.format(names=names)
   #Hi, hilary. I am vergil and this is nero.
)
print(
   'Three people:{0[0]}, {0[1]}, {0[2]} from three places:{1[0]}, {1[1]}, {1[2]}.'.format(names,places)
   #Three people:hilary, vergil, nero from three places:chengdu, shijiazhuang, tokyo.
)

#进制转换
print(
   '{0:b}, {0:o}, {1:d}, {1:x}'.format(256,512)
   #100000000, 400, 512, 200
)
#逗号分隔
print(
   '{:,}'.format(12345678)
   #12,345,678
)
#浮点数格式
print(
   '{:+12.3f}'.format(3.14159265358979)
   #      +3.142
)
#对齐与填充
print(
   '{:>010}'.format(12), #右对齐,宽度10,填充0
   '{:0<+12.3f}'.format(-12.34567),#填充0,左对齐,保留正负号,宽度12,保留3位小数
   '|{:^10}|'.format(3) #,默认填充空格,居中对齐,宽度10
   #0000000012 -12.34600000 |    3     |
)

来源:https://blog.csdn.net/Hilavergil/article/details/79161590

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com