python - 旧式字符串格式需要显式 str() 转换吗?

标签 python string string-formatting

我正在维护一个旧的 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 using str()).

关于python - 旧式字符串格式需要显式 str() 转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782020/

相关文章:

java - 如何让 printf %x 类似于 python

python - 如何使用python去除图像中的椒盐噪声?

c++ - 关于C++字符指针的问题

python - 在 Python 中换行

c# - 在c#中解析一个字符串

c++ - 如何通过 #define 函数向格式化字符串函数调用添加参数

java - String.format 不允许 int

python - 如何使用 python bottle 创建用户密码登录网页

python - 将 PostGIS 几何类型作为几何类型从 Shapely 导入 Python?

python - 提交后 SQLAlchemy 没有设置自动增量的主键