您好,我目前正在学习如何在 python 2.7 中使用字符串格式,我对特定场景中产生的某些错误消息感到有点困惑。
好的,我编写的第一段代码按预期运行,即:
print "My name is %s and my age is %d years old!" % ('Bob', 30)
Run Code Online (Sandbox Code Playgroud)第二段稍作修改的代码也运行良好(使用两次转换):
print "My name is %s and my age is %s years old!" % ('Bob', 30)
Run Code Online (Sandbox Code Playgroud)然而,第三段代码输出和错误(使用一(d)和一(s)转换):
print "My name is %d and my age is %s years old!" % ('Bob', 30)
Run Code Online (Sandbox Code Playgroud)在场景 3 中,我收到错误消息:
%d format: a number is required, not str
Run Code Online (Sandbox Code Playgroud)
所以我的问题是为什么允许场景 2(将转换放在预期的小数上),但场景 3 中不允许相反的方式。谢谢,我希望我尽可能地解释了我的问题。
有一种更好的方法来格式化 python 中的字符串(您可能感兴趣)。对象类型并不重要。按列表
"{0}-{1}: {2}".format(1,"foo",True)
Run Code Online (Sandbox Code Playgroud)
通过字典
"{num}-{string}: {bool}".format(**{"num":1,"string":"foo","bool":True})
Run Code Online (Sandbox Code Playgroud)
更多信息:https ://docs.python.org/2/library/stdtypes.html#str.format
它应该是
print "My name is %s and my age is %d years old!" % ('Bob', 30)
Run Code Online (Sandbox Code Playgroud)
抛出错误是因为它期望整数值%d但得到一个字符串%s
但int 可以转换为 string所以之前的情况不受影响