我正在维护一个旧的 Python 代码库,其中散布着一些非常奇怪的习语。我遇到的一件事是使用百分比编码样式的字符串格式:
'Error %s: %s' % (str(err), str(message))
忽略现代字符串插值的.format()
的存在,我的问题是:
是否有必要使用 str()
显式转换 %s
参数,或者这正是 %s
所做的?
最佳答案
不,不需要显式的 str()
调用,%s
格式化程序包含一个 str()
已经调用:
>>> class Foo(object):
... def __str__(self):
... return "I am a string for Foo"
...
>>> '%s' % Foo()
'I am a string for Foo'
这也明确记录在 String Formatting Operations section 中:
's'
String (converts any Python object usingstr()
).
关于python - 旧式字符串格式需要显式 str() 转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782020/