use*_*300 178 python string typeerror output-formatting python-3.x
该程序应该采用两个名称,如果它们的长度相同,则应检查它们是否是同一个单词.如果它是相同的单词,它将打印"名称相同".如果它们长度相同但字母不同,则会打印"名称不同但长度相同".我遇到问题的部分是在底部4行.
#!/usr/bin/env python
# Enter your code for "What's In (The Length Of) A Name?" here.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
if name1 == name2:
print ("The names are the same")
else:
print ("The names are different, but are the same length")
if len(name1) > len(name2):
print ("'{0}' is longer than '{1}'"% name1, name2)
elif len(name1) < len(name2):
print ("'{0}'is longer than '{1}'"% name2, name1)
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,它显示:
Traceback (most recent call last):
File "program.py", line 13, in <module>
print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)
任何建议都非常感谢.
nne*_*neo 197
你正在混合不同的格式功能.
旧式%格式化使用%代码进行格式化:
'It will cost $%d dollars.' % 95
Run Code Online (Sandbox Code Playgroud)
新式{}格式使用{}代码和.format方法
'It will cost ${0} dollars.'.format(95)
Run Code Online (Sandbox Code Playgroud)
请注意,对于旧式格式,您必须使用元组指定多个参数:
'%d days and %d nights' % (40, 40)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,由于您使用的是{}格式说明符,请使用.format:
"'{0}' is longer than '{1}'".format(name1, name2)
Run Code Online (Sandbox Code Playgroud)
leo*_*onh 46
错误在于您的字符串格式.
使用'%'运算符使用传统字符串格式的正确方法是使用printf样式的格式字符串(此处为Python文档:http://docs.python.org/2/library/string.html#format-字符串语法):
"'%s' is longer than '%s'" % (name1, name2)
Run Code Online (Sandbox Code Playgroud)
但是,'%'运算符将来可能会被弃用.新的PEP 3101做事方式是这样的:
"'{0}' is longer than '{1}'".format(name1, name2)
Run Code Online (Sandbox Code Playgroud)
Nic*_*ady 44
对我来说,当我试图将元组传递给字符串格式方法时,会导致此错误.
从链接复制并粘贴正确的答案(不是我的工作):
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
使用感兴趣的元组作为唯一项目,即(thetuple,)部分,使单个元组成为关键位.
小智 7
请记住,此错误也可能是由于忘记引用变量而引起的
"this is a comment" % comment #ERROR
Run Code Online (Sandbox Code Playgroud)
代替
"this is a comment: %s" % comment
Run Code Online (Sandbox Code Playgroud)
小智 6
除了其他两个答案,我认为缩进在最后两个条件下也是不正确的。条件是一个名字要长于另一个名字,并且它们必须以“ elif”开头且没有缩进。如果将其放在第一个条件下(通过从边缘开始给它四个缩进),则最终会矛盾,因为名称的长度不能同时相等且不同。
else:
print ("The names are different, but are the same length")
elif len(name1) > len(name2):
print ("{0} is longer than {1}".format(name1, name2))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
469508 次 |
| 最近记录: |