2022年 11月 8日

Python几种基本的字符串格式化方法

1.旧式 % 格式化

% 百分号格式化和 C 语言的 printf 格式化差不多。

  1. # '%%' 格式化成 '%'
  2. print('%% %d' % 1) #输出百分号和数字
  3. # %c 字符及其ASCII码
  4. print('%c' % 48) #输出ascii码48对应的0
  5. # %s 字符串
  6. # %d 十进制有符号整数
  7. # %u 十进制无符号正数
  8. # %o 八进制无符号数
  9. # %x 十六进制无符号数
  10. # %X 十六进制无符号数,大写字母
  11. # %e 浮点数科学计数法
  12. # %E 浮点数科学计数法,大写E
  13. # %f 浮点数,小数点表示
  14. print('%f' % 1.1) #输出1.100000默认六位小数
  15. print('%.2f' % 1.1) #指定两位小数
  16. # %g 浮点数,根据值大小采用 %e 或 %f
  17. # %G 参照%g
  18. # %p 十六进制地址
  19. # %n 存储输出字符的数量放进参数列表的下一个变量中
  20. # 多个参数时,可以用括号括起来
  21. print('%d %s' % (999,'yyds'))
  22. # 也可以用字典key来获取对应值
  23. print('%(id)d %(str)s' % {'str':'yyds','id':999})

2.str.format() 方法

后来引入了一个新的字符串格式化的方法,str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 接受任意个参数,位置可以不按顺序。

  1. #顺序查找
  2. print('{} and {} and {}'.format(1, 2, 3))
  3. #指定位置
  4. print('{2} and {1} and {0}'.format(1, 2, 3))
  5. #通过参数名
  6. print('{one} and {two} and {three}'.format(one=1,three=3,two=2))
  7. #进行格式化
  8. print('{one:d} and {two:.2f} and {three:s}'.format(one=1,three='three',two=2))
  9. #取单个字符
  10. print('{str[0]}'.format(str='hello world'))
  11. #根据宽度对齐,^、<、>分别是居中、左对齐、右对齐
  12. #全部为10个字符宽度左对齐
  13. print('name={: <10s} score={: <10.1f}'.format('gong',79.5))
  14. print('name={: <10s} score={: <10.1f}'.format('jianbo',67))

参考文档:string — 常见的字符串操作 — Python 3.10.2 文档 

3.f-string格式化字符串字面值(Python3.6+)

格式字符串字面值 或称 f-string 是标注了 ‘f’ 或 ‘F’ 前缀的字符串字面值。这种字符串可包含替换字段,即以 {} 标注的表达式。其他字符串字面值只是常量,格式字符串字面值则是可在运行时求值的表达式,会使用 format() 协议进行格式化。除非字面值标记为原始字符串,否则,与在普通字符串字面值中一样,转义序列也会被解码。

  1. name='gongjianbo'
  2. print(f'hello {name}')
  3. print(F'hello {name}')
  4. table=[{'name':'gong','score':79.5},{'name':'jianbo','score':67}]
  5. for people in table:
  6. print(f'name={people["name"]: <10s} score={people["score"]: <10.1f}')
  7. a=10
  8. b=15
  9. print(f'a+b={a+b}')

参考文档:2. 词法分析 — Python 3.10.2 文档

4.模板字符串

模板字符串是一种较为简单的字符串替换方式。模板字符串的一个主要用例是文本国际化 (i18n),因为在此场景下,更简单的语法和功能使得文本翻译过程比使用 Python 的其他内置字符串格式化工具更为方便。

  1. from string import Template
  2. t = Template('$who likes $what')
  3. s = t.substitute(who='lu', what='ma')
  4. print(s) #输出 'lu likes ma'

创建模板后,可以用 substitute 或者 safe_substitute 进行替换,主要区别是 safe 版本未找到就返回原占位符不触发异常。

参考文档:string — 常见的字符串操作 — Python 3.10.2 文档