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

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

最佳答案

您正在混合使用不同的格式函数。

旧式 % 格式使用 % 代码进行格式设置:

'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)

https://stackoverflow.com/questions/18053500/

相关文章:

python - Python中的SFTP? (平台无关)

linux - 如何删除shell中最后10个命令的历史记录?

linux - 如何提取 filename.tar.gz 文件

linux - IOCTL Linux 设备驱动程序

python - 如何从 Visual Studio Code 中执行 Python 代码

python - Pandas 在没有标题的表格中读取

python - 在 Python : x**. 5 或 math.sqrt(x) 中哪个更快?

linux - 如何从命令行在 GNOME 终端中打开一个新选项卡?

python - Django:登录后重定向到上一页

linux - 检查 Bash 列表中是否存在变量