message = "hello %s , how are you %s, welcome %s"%("john","john","john")
避免指定“john”3 次而是指定一个短语的最 Pythonic 方式是什么。
最佳答案
我不会使用 %
格式,.format
有很多优点。此外,最初计划删除 %
格式并用 .format
替换它,尽管显然这实际上并没有发生。
A new system for built-in string formatting operations replaces the
%
string formatting operator. (However, the%
operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.
>>> "hello {name}, how are you {name}, welcome {name}".format(name='john')
'hello john, how are you john, welcome john'
我更喜欢第一种方式,因为它是明确的,但这就是为什么 .format
优于 %
格式
>>> "hello {0}, how are you {0}, welcome {0}".format('john')
'hello john, how are you john, welcome john'
https://stackoverflow.com/questions/11921649/