设置字符串格式
这里的基本思想是对字符串调用方法format()并提供设置其格式的的值。
注意用{}括起来的字符串
替换字段名
#最简单情况,一一对应代换
>>> "{},{},{},{}".format(1,3,4,6)
'1,3,4,6'
>>> "{foo},{}{fab}".format(5,foo=6,fab=10)
'6,510'
'''注意:在“”中只有{foo}与{}之间有“,”所以输出时只有一个“,”'''
fullname=["Alice","Sto"]
print("abc,{nmae[1]}".format(nmae=fullname))
输出:abc,Sto
基本转换
str="The number is {num}.".format(num=42)
print(str)
str="The number is {num:f}".format(num=42)#{num:f}表示num为实型
print(str)
str="The number is {num:b}".format(num=42)#num二进制输出
print(str)
str="The number is {num:e}".format(num=42.0543)#科学表示法
print(str)
#E与e相同
#%将数表示成百分数
#。。。
输出:
The number is 42.
The number is 42.000000
The number is 101010
The number is 4.205430e+01
宽度:
str="{num:10}".format(num=3)#设置宽度为10
print("'"+str+"'")
str="{num:10}".format(num="Bob")
print("'"+str+"'")
输出:
' 3'
'Bob '
精度:
import math
Str="{pi:5.2f}".format(pi=math.pi)
print(Str)
输出:
3.14(宽度为5)
不仅可以对数值制定精确度,其他类型也可以,只是不常见
str="{:.5}".format("123456789")
print(str)
输出:
12345
符号、对齐和用0填充
import math
str="'{:010.2f}'".format(math.pi)
print(str)
输出:
'0000003.14'
对其方式:
要指定左对齐、右对齐、和居中用<、>和^
import math
print("'{0:<10.2f}'".format(math.pi))
print("'{0:>10.2f}'".format(math.pi))
print("'{0:^10.2f}'".format(math.pi))
输出:
'3.14 '
' 3.14'
' 3.14 '
print("'{:#^10.2f}'".format(math.pi))
输出:
'###3.14###'