Python format() 格式化
程序员文章站
2022-07-14 23:48:35
...
Python 2.6
Python 中 format 方法所做的事情便是将每个参数值替换至格式所在的位置。
1、通过位置来填充字符串
一个字符串可以使用某些特定的格式(Specification),随后, format 方法将被调用,使用这一方法中与之相应的参数替换这些格式。
请注意,Python 从 0 开始计数,这意味着索引中的第一位是 0,第二位是1,以此类推。
name='Swaroop';
age=20;
print("{0} was {1} years old when he wrote this book".format(name,age));
print("Why is {0} playing with that python".format(name));
$ python str_format.py
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python
* 注意数字只是一个可选选项。
name='Swaroop';
age=20;
print("{} was {} years old when he wrote this book".format(name,age));
print("Why is {} playing with that python".format(name));
运行结果相同。
2、其他 ???
#对于浮点数‘0.333’ 保留小数点(.)后三位
print('{0:.3f}'.format(1.0/3))
#使用下划线填充文本,并保持文字处于中间位置
#使用(^)定义'___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
#基于关键词输出'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop',book='A Byte of Python'))
$ python helloWorld.py
0.333
___hello___
Swaroop wrote A Byte of Python