TypeError:在字符串格式化python期间并非所有参数都转换了

新手上路,请多包涵

该程序应该接受两个名称,如果它们的长度相同,它应该检查它们是否是同一个单词。如果是同一个词,它将打印 “The names are the same” 。如果它们的长度相同但字母不同,它将打印 “The names are different but the same length” 。我遇到问题的部分在底部的 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)

当我运行此代码时,它显示:

 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

原文由 user2652300 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 466
1 个回答

您正在混合不同的格式功能。

旧式 % 格式化使用 % 格式化代码:

 'It will cost $%d dollars.' % 95

新式 {} 格式化使用 {} 代码和 .format 方法

'It will cost ${0} dollars.'.format(95)

请注意,对于旧式格式,您必须使用元组指定多个参数:

 '%d days and %d nights' % (40, 40)


在您的情况下,由于您使用的是 {} 格式说明符,请使用 .format

 "'{0}' is longer than '{1}'".format(name1, name2)

原文由 nneonneo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题