在 Python 中进行字符串格式化时,我注意到 %s
也将数字转换为字符串。
>>> a = 1
>>> b = 1.1
>>> c = 'hello'
>>> print 'Integer: %s; Float: %s; String: %s' % (a, b, c)
Integer: 1; Float: 1.1; String: hello
我不知道其他变量类型,但是像这样使用 %s
安全吗?
这肯定比每次都指定类型要快。
最佳答案
使用 %s
自动调用变量上的 str
。由于所有内容都已定义 __str__
,因此您应该能够毫无问题地执行此操作(即不会引发异常)。然而,你实际打印的是另一回事......
请注意,在较新的 python 代码中,还有另一个选项使用 format
方法:
'Integer: {}; Float: {}; String: {}'.format(a,b,c)
这基本上以相同的方式工作,只是一旦你学习了语法它就更强大了。
关于python - Python 中的字符串格式 : can I use %s for all types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14506430/