Skip to main content
 首页 » 编程设计

python之字符串格式化程序 `% + tuple` 是否已弃用

2024年10月01日31zlslch

在python中有两种格式化字符串的方法:

  • 使用 % 后跟一个元组:

    '%s %s' % ('one', 'two') 
    
  • 使用格式:

    '{} {}'.format('one', 'two') 
    

PyFormat webpage有一个非常好的格式化选项列表。 但是我注意到他们将 % + tuple 方法称为“OLD”(而不是经典名称或其他非负名称)

我的问题很简单:“旧”方法是否已弃用,因此我们应该使用 format,还是两种方法都可以使用?

看起来 format 更强大,可以做“旧”方法做不到的事情。

请您参考如下方法:

即使不谈性能,因为在 python 3 中 % 可以 被删除,format 是首选。

Old string formatting :

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.