| 符号 | 说明 |
|---|---|
| %s | 格式化字符串(采用str()显示) |
| %c | 格式化单个字符及其ASCII码 |
| %d或%i | 十进制整数 |
| %x | 十六进制整数 |
| %f或%F | 浮点数字,可指定小数点后的精度 |
| %o | 八进制整数 |
| %r | 使用 repr() 函数将表达式转换为字符串 |
| %e | 指数 (基底写为e) |
| %E | 指数 (基底写为E) |
| %g | 智能选择使用 %f 或 %e 格式 |
| %G | 智能选择使用 %F 或 %E 格式 |
| %% | 字符"%" |
语法格式:
“%[-][+][0][m][.n]格式化字符串”%exp
参数说明:
-:可选参数:用于指定左对齐,正数前方无符号,负数前面加负号
+:可选参数: 用于指定右对齐,正数前方加正号,负数前方加负号
0:可选参数: 表示右对齐,正数前方无符号,负数前方加负号,用0填充空白(一般与m参数一起使用)
m:可选参数: 表示占用宽度
.n:可选参数: 表示小数点后保留的位数
#左对齐,加上负号
#%的后面添加数字n,表示至少显示n位,不足时用空格补齐,超过n则正常显示所有字符
#对于数字而言,可以在左侧补0,%0nd,n是任意自然数
#前后的参数的数量必须一致
info='我叫%-5s,你叫%-5s,他叫%-5s,今年是%-05d年'%('吴彦祖','彭于晏南京分晏','周杰伦',2020)
print(info)
我叫吴彦祖 ,你叫彭于晏南京分晏,他叫周杰伦 ,今年是2020 年 Process finished with exit code 0
#右对齐
info='我叫%5s,你叫%5s,他叫%5s,今年是%5s年'%('吴彦祖','彭于晏南京分晏','周杰伦','2020')
print(info)
我叫 吴彦祖,你叫彭于晏南京分晏,他叫 周杰伦,今年是 2020年 Process finished with exit code 0
#%m.nf m表示最少显示多少位,不足用空格补齐,n表示保留n位小数 number1='%6.1f'%(3.68) print(number1)
3.7 Process finished with exit code 0三、使用str.format()
- 补齐{:n} n表示最少显示n位
str1='My name is {:6},Your name is {:6},age is {:6}'.format('吴彦祖','彭于晏',23)
print(str1)
My name is 吴彦祖 ,Your name is 彭于晏 ,age is 23 Process finished with exit code 0
- 大于号表示右对齐,小于号表示左对齐,^表示居中对齐
str1='My name is {:<6},Your name is {:^6},age is {:>6}'.format('吴彦祖','彭于晏',23)
print(str1)
My name is 吴彦祖 ,Your name is 彭于晏 ,age is 23 Process finished with exit code 0
- 随意补0
str1='My name is {:<06},Your name is {:^06},age is {:>06}'.format('吴彦祖','彭于晏',23)
print(str1)
My name is 吴彦祖000,Your name is 0彭于晏00,age is 000023 Process finished with exit code 0
- 补特殊字符的方案,加在:后面
str1='My name is {:@<06},Your name is {:*^06},age is {:->06}'.format('吴彦祖','彭于晏',23)
print(str1)
My name is 吴彦祖@@@,Your name is *彭于晏**,age is ----23 Process finished with exit code 0
- 前后参数的数量,如果前面比后面多,会报错,如果后面的比前面的多,则不会报错
str1='My name is {:>6},Your name is {:<6},age is {:^6}'.format('吴彦祖','彭于晏',23,24)
print(str1)
My name is 吴彦祖,Your name is 彭于晏 ,age is 23 Process finished with exit code 0
- 下标取值法
str1='My name is {1:>6},Your name is {0:<6},age is {3:^6}'.format('吴彦祖','彭于晏',23,24)
print(str1)
My name is 彭于晏,Your name is 吴彦祖 ,age is 24 Process finished with exit code 0
- 如果本来就想显示{},用{{}},如果里面的值仍然想使用参数,用{{{}}}
str1='My name is {{{1:>6}}},Your name is {0:<6},age is {3:^6}'.format('吴彦祖','彭于晏',23,24)
print(str1)
My name is { 彭于晏},Your name is 吴彦祖 ,age is 24
Process finished with exit code 0
四、f-string格式化字符串(Python3.6 版本以上)
name1='吴彦祖'
name2='彭于晏'
print(f'My name is {name1:^7},Your name is {name2:^7}')
My name is 吴彦祖 ,Your name is 彭于晏 Process finished with exit code 0
name = "testerzhang"
print(f'Hello {name}.')
print(f'Hello {name.upper()}.')
d = {'id': 1, 'name': 'testerzhang'}
print(f'User[{d["id"]}]: {d["name"]}')
Hello testerzhang. Hello TESTERZHANG. User[1]: testerzhang Process finished with exit code 0



