Python格式化字符串的使用

225 阅读2分钟

格式化字符串

在实际运用中我们会时常要使用到字符串的格式化,因为这样相比较而言要更加的简单清楚,比如如果我们有一个变量为price, 我们要输出苹果的价格是xx元,如果不使用格式化字符串,我们可能要使用

print("苹果的价格是", price, "元")

但是如果使用格式化字符串,我们只要使用

print("苹果的价格是{}元".format(price))

这样使用格式化字符串尤其的方便,而且其功能十分强大 在这里我们推荐使用str.format来实现字符串格式化,另外一种使用%的不在这里讨论

使用

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

print("输入的数字为{}, 它的2倍是{}".format(num, 2*num))
# 假设输入为2 , 输出
# 输入的数字为2,它的2倍为4

指定位置

print("Hello {0}, your age is {2}, your is {1} cm tall".format('Cyberist', 175, 20))
# 输出
# Hello Cyberist, your age is 20, your is 175 cm tall

使用元组,列表格式化

data_1 = ("Cyberist", 2019)
data_2 = []"Cyberist", 2019]
print("Hello {0[0]}, today is {0[1]}".format(data_1))
print("Hello {0[0]}, today is {0[1]}".format(data_2))
# 输出均为
# Hello Cyberist, today is 2019

使用关键词

print('Hello {name}, today is {year}'.format(name='Cyberist', year=2019))

使用字典进行格式化

data = {"name":"Cyberist", "age":20}
print("Hello {name}, today is {age}".format(**data))

保留小数位数

print("The price is {:.2f}元".format(3)) # 保留两位小数
# 输出
# The price is 3.00元
print("The price is {:.0f}元".format(3.43)) # 只保留整数部分
# 输出
# The price is 3元

控制宽度,填充字符

print("Hello this char is 8 width {:8}".format(8)) # 占位8个字符
print("The width is {:x<4d}".format(4)) # 字符宽度为4,以x向右填充
# 输出
# The width is 4xxx
print("The width is {:x>4d}".format(4)) # 字符宽度为4,以x向左填充
# 输出
# The width is xxx4
print("The width is {:x>4d}".format(4)) # 字符宽度为4,居中显示,其余用x补充
# 输出
# The width is x4xx

分隔显示数字

print('Hello, the num is {:,}'.format(100000000)) # 以逗号分隔数字
# 输出
# Hello, the num is 100,000,000

使用其他进制显示

{:x} -> 使用十六进制
{:#x} -> 使用十六进制,但有前缀0x, 并使用小写
{:#X} -> 使用十六进制,但有前缀0X,并使用大写
{:o} -> 使用八进制
{:b} -> 使用二进制
{:d} -> 使用十进制

输出 { }

print("{}是{{}}".format("大括号"))
# 输出
# 大括号是{}