Python3-2020-测试开发-3- 字符串format格式化和数字格式化

一、format()用法

1. 简单用法:

'''
format()用法:

'''

a1 = "name is  {0} ,age is {1:#^8},{0} is my girlfriend"
a2 = "name is  {0} ,age is {1:#<8},{0} is my girlfriend"
a3 = "name is  {0} ,age is {1:#>8},{0} is my girlfriend"
b = "name is  {name} ,age is {age},{name} is my girlfriendy"

print(a1.format("宝宝",18))
print(b.format(name = "宝贝",age = 19))

输出:

name is  宝宝 ,age is ###18###,宝宝 is my girlfriend
name is  宝贝 ,age is 19,宝贝 is my girlfriendy

2. 填充和对齐

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

print(a1.format("宝宝",17))
print(a2.format("宝宝",17))
print(a3.format("宝宝",17))

输出:

name is  宝宝 ,age is ###18###,宝宝 is my girlfriend
name is  宝贝 ,age is 19,宝贝 is my girlfriendy
name is  宝宝 ,age is ###17###,宝宝 is my girlfriend
name is  宝宝 ,age is 17######,宝宝 is my girlfriend
name is  宝宝 ,age is ######17,宝宝 is my girlfriend

二、数字格式化

'''数字格式化'''

a4 = "我是{0},我的余额为{1:.2f}"

print(a4.format("宝宝",666666.666666))   # 保留小数点后两位:我是宝宝,我的余额为666666.67
print("{:+.2f}".format(88888.8888))      # 带符号保留小数点后两位:+88888.89
print("{:.0f}".format(777.99))           # 不带小数 :778
print("{:0>2d}".format(9))               # 数字补0,填充左边,宽度为2:09
print("{:#<4d}".format(9))               # 数字补0,填充右边,宽度为4:9###
print("{:,}".format(10000000))           # 以逗号分隔的数字格式:10,000,000
print("{:.2%}".format(0.25))             # 百分比格式,保留小数2位:25.00%
print("{:.0%}".format(0.25))             # 百分比格式,保留小数0位:25%
print("{:.2e}".format(2))                # 指数记法 :2.00e+00
print("{:10d}".format(18))               # 默认,宽度为10:        18
print("{:<10d}".format(18))              # 左对齐,宽度为10:18
print("{:^10d}".format(18))              # 居中,宽度为10:    18

输出:

我是宝宝,我的余额为666666.67
+88888.89
778
09
9###
10,000,000
25.00%
25%
2.00e+00
        18
18        
    18    
原文地址:https://www.cnblogs.com/chushujin/p/12818675.html