Python字符串格式化常用方法:
**
一、百分号方式格式化
**'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
注:
1.%s可以代表任何,若不确定类型的话,%s通用。
2.转义%可使用%%来进行转义。
二、format方式
"i am {}, age {}, {}".format("zjh", 7, 'hello') #必须一一对应位置
Out[1]: 'i am zjh, age 7, hello'
"i am {0}, age {1}, really {0}".format("zjh", 7) #按照索引对应
Out[2]: 'i am zjh, age 7, really zjh'
"i am {name}, age {age}, really {name}".format(name="zjh", age=7) #按照类似字典的方式对应
Out[3]: 'i am zjh, age 7, really zjh'
"numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
#分别是2进制 8进制 10进制 x与X: 16进制 %:百分比
Out[4]: 'numbers: 1111,17,15,f,F, 1587.623000%'
三、f-string
>>> name = 'Fred'
>>> age = 42
>>> f'He said his name is {name} and he is {age} years old.'
He said his name is Fred and he is 42 years old.
1.可以使用f或者F前缀;
2.‘{}’内可以进行计算、插入函数;
自定义格式:
f-string采用 {content:format} 设置字符串格式,其中 content 是替换并填入字符串的内容,可以是变量、表达式或函数等,format 是格式描述符。采用默认格式时不必指定 {:format},如上面例子所示只写 {content} 即可。
- 格式描述符 含义与作用
- < 左对齐(字符串默认对齐方式)
- > 右对齐(数值默认对齐方式)
- ^ 居中
详细教程:
https://blog.csdn.net/sunxb10/article/details/81036693