1. %占位符
概念 and python 实例
%是字符串运算符,被称为格式化操作符。%左边是模版或者格式化字符串,右边是容器,包含替换格式字符串的变量值。
name = 'Jack'
age=18
print('%s is %d years old.'%(name,age))
output:
Jack is 18 years old.
可见,右边容器变量个数必须和左边占位符的数目一致。在用变量值替换占位符的过程中,从左到右依次读取变量,按顺序替代占位符的位置。
格式化字符串转换符 表


d i 都是整数;

%o: oct 八进制
%d: dec 十进制
%x hex16进制

%f ——保留小数点后面六位有效数字
%.3f,保留3位小数位
%e ——保留小数点后面六位有效数字,指数形式(e表示幂)输出
%.3e,保留3位小数位,使用科学计数法
%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
%.3g,保留3位有效数字,使用小数或科学计数法
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。

reference:
https://www.cnblogs.com/tonson/p/8672322.html
2. format
2.1基础语法
format可以实现%所实现的,但功能更强大
三种方法:
1.不带字段
‘{} {}’.format(x,xx)
print('{} and {}'.format('hello','world')) #{}中不带字段
output:
hello and world
2.带字段 数字/关键字
数字:
'{0} and {1}.format(x,xx)
print('{0} {1} {0}'.format('hello','world'))#{}中带字段
output:
hello world hello
关键字:
‘{a} and {b}’.format(a=x,b=xx
print('{a} {b}'.format(a='hello',b='world'))#{}中带关键字
hello world
2.2 高阶
print('{:20s}'.format('1'))
{:20s } 意思是取20位字符,并把format里的内容左对齐(默认,符号<)
print('{:20s}'.format('1')) #左对齐
print('{:>20s}'.format('1')) #右对齐
print('{:<20s}'.format('1')) #左对齐
print('{:^20s}'.format('1')) #居中对齐
^居中对齐, <左对齐,>右对齐;
output:
1
1
1
1
‘b’ - 二进制。将数字以2为基数进行输出。
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。
‘d’ - 十进制整数。将数字以10为基数进行输出。
‘o’ - 八进制。将数字以8为基数进行输出。
‘x’ - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
‘g’ - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。
print('{:10s} and {:>10s}'.format('hello','world'))
output:
hello and world
10s也可以换成20f,则为浮点数,默认小数点后6位。也可以截取x位如:{:.xf}
print('{} is {:f}'.format(1.123,1.123)) # 取2位小数
print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
output
1.123 is 1.123000
1.123 is 1.12
print('{0:b}'.format(3))
print('{:o}'.format(20))
print('{:x}'.format(20))
print('{0:b}'.format(10))
print('{0:^6b}'.format(10))
print('{:e}'.format(20))
print('{:%}'.format(0.2))
output:
11
24
14
1010
1010
2.000000e+01
20.000000%
本文介绍了Python中的字符串格式化方法,包括%占位符的使用,如%d、%f等格式化转换符,以及format函数的基础语法和高阶应用,如指定对齐方式和精度。
1505

被折叠的 条评论
为什么被折叠?



