TypeError: not all arguments converted during string formatting python(TypeError:在字符串格式化python期间并非所有参数都转换了)
问题描述
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
Any suggestions are highly appreciated.
You're mixing different format functions.
The old-style %
formatting uses %
codes for formatting:
'It will cost $%d dollars.' % 95
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)
In your case, since you're using {}
format specifiers, use .format
:
"'{0}' is longer than '{1}'".format(name1, name2)
这篇关于TypeError:在字符串格式化python期间并非所有参数都转换了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:在字符串格式化python期间并非所有参数都转换了
基础教程推荐
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01