【format】 vs 【%】 in Python

待我称王封你为后i 2022-06-01 01:29 289阅读 0赞

相比【%】,Python中的【format】更显精致,对于【%】来说,它无法同时传递一个变量和元组(Tuple)

比如,对于:

“hi there %s” % name

如果name传递Tuple元组类型参数,那么将抛出如下错误:

TypeError: not all arguments converted during string formatting

为保证其正常执行,你需要这么做,确保参数name为只包含单个元素的元组:

“hi there %s” % (name,) # supply the single argument as a single-item tuple

  1. def format_with_format(obj):
  2. try:
  3. return 'hello {name}'.format(name=obj)
  4. except Exception as e:
  5. print(e)
  6. return 'format_with_format error'
  7. def format_with_percent(obj):
  8. try:
  9. return 'hello %s' % obj
  10. except Exception as e:
  11. print(e)
  12. return 'format_with_percent error'
  13. def format_with_percent_optimization(obj):
  14. try:
  15. return 'hello %s' % (obj,)
  16. except Exception as e:
  17. print(e)
  18. return 'format_with_percent error'
  19. if __name__ == '__main__':
  20. L = [1, 2, 3]
  21. T = (1, 2, 3, 4)
  22. print(format_with_format(L))
  23. print(format_with_format(T))
  24. print(format_with_percent(L))
  25. print(format_with_percent(T))
  26. print(format_with_percent_optimization(T))

这里写图片描述
https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Not in GZIP format异常

    背景 开发中解压缩和压缩文件的处理是很常遇到的情况。这几天做一个对账的功能的时候,遇到过一个解压gzip压缩文件,报错:Not in GZIP format 的异常问题。