TypeError:并非所有参数都在字符串格式化python期间转换 [英] TypeError: not all arguments converted during string formatting python

查看:89
本文介绍了TypeError:并非所有参数都在字符串格式化python期间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序应该接受两个名字,如果它们的长度相同,它应该检查它们是否是同一个词.如果是同一个词,它将打印名字相同".如果它们的长度相同但字母不同,它将打印名称不同但长度相同".我有问题的部分在底部 4 行.

The program is supposed to take in two names, and if they are the same length it should check if they are the same word. If it's the same word it will print "The names are the same". If they are the same length but with different letters it will print "The names are different but the same length". The part I'm having a problem with is in the bottom 4 lines.

#!/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)

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

When I run this code it displays:

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

非常感谢任何建议.

推荐答案

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

You're mixing different format functions.

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

The old-style % formatting uses % codes for formatting:

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

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

The new-style {} formatting uses {} codes and the .format method

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

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

Note that with old-style formatting, you have to specify multiple arguments using a tuple:

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

<小时>

就您而言,由于您使用的是 {} 格式说明符,请使用 .format:


In your case, since you're using {} format specifiers, use .format:

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

这篇关于TypeError:并非所有参数都在字符串格式化python期间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆