Python中有3种format字符串的方式:

  • 传统C语言式
  • 命名参数
  • 位置参数

1. 传统C语言式

和c语言里面的 sprintf 类似,参数格式也一样

title =  "world"
year = 2013
print "hello %s, %10d" % (title, year)

这种方式有一个陷阱,比如 title 是一个list,执行语句 "hello %s" % title,会触发一个异常;正确的做法是先把 title 转换为 string,或用 string.format

2. 命名参数

title = "world"
year = 2013
print "hello %(title)s, %(year)10d" % {"title":title, "year":year}

string.format 也支持命名参数:

"hello {title}, {year}".format(title=title, year=year)
"hello {title}, {year}".format(**{"title":title, "year":year})

string.format还有一个地方需要注意,如果参数是unicode,则string也必须是unicode,否则,会触发异常。如执行下述语句会出错:

title = u"标题党"
"hello {0}".format(title)

3. 位置参数

title = "world"
year = 2013
print "hello {0}, {1}".format(title, year)

print "today is {0:%Y-%m-%d}".format(datetime.datetime.now())

总结

string.format 比 % 格式化方式更优雅,不容易出错

参考

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2021-09-06
  • 2021-06-21
  • 2023-03-18
猜你喜欢
  • 2021-12-11
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2022-02-05
相关资源
相似解决方案