TypeError:并非所有参数都在字符串格式化python期间转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18053500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: not all arguments converted during string formatting python
提问by user2652300
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.
该程序应该接受两个名字,如果它们的长度相同,它应该检查它们是否是同一个词。如果是同一个词,它将打印"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)
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.
任何建议都非常感谢。
回答by nneonneo
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
新式{}
格式化使用{}
代码和.format
方法
'It will cost '%d days and %d nights' % (40, 40)
dollars.'.format(95)
Note that with old-style formatting, you have to specify multiple arguments using a tuple:
请注意,对于旧式格式,您必须使用元组指定多个参数:
"'{0}' is longer than '{1}'".format(name1, name2)
In your case, since you're using {}
format specifiers, use .format
:
在您的情况下,由于您使用的是{}
格式说明符,请使用.format
:
"'%s' is longer than '%s'" % (name1, name2)
回答by leonh
The error is in your string formatting.
错误在于您的字符串格式。
The correct way to use traditional string formatting using the '%' operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):
使用 '%' 运算符使用传统字符串格式的正确方法是使用 printf 样式的格式字符串(此处的 Python 文档:http: //docs.python.org/2/library/string.html#format-字符串语法):
"'{0}' is longer than '{1}'".format(name1, name2)
However, the '%' operator will probably be deprecated in the future. The new PEP 3101way of doing things is like this:
但是,将来可能会弃用“%”运算符。新的PEP 3101做事方式是这样的:
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))
回答by GuyP
In addition to the other two answers, I think the indentations are also incorrect in the last two conditions. The conditions are that one name is longer than the other and they need to start with 'elif' and with no indentations. If you put it within the first condition (by giving it four indentations from the margin), it ends up being contradictory because the lengths of the names cannot be equal and different at the same time.
除了其他两个答案,我认为缩进在最后两个条件中也是不正确的。条件是一个名称比另一个长,并且它们需要以“elif”开头并且没有缩进。如果你把它放在第一个条件中(通过给它从边距四个缩进),它最终是矛盾的,因为名称的长度不能同时相等和不同。
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)
回答by Nick Brady
For me, This error was caused when I was attempting to pass in a tuple into the string format method.
对我来说,这个错误是当我试图将一个元组传入字符串格式方法时引起的。
I found the solution from this question/answer
Copying and pasting the correct answer from the link (NOT MY WORK):
从链接中复制并粘贴正确答案(不是我的作品):
_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting
Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.
用感兴趣的元组作为唯一项制作一个单例元组,即 (thetuple,) 部分,是这里的关键。
回答by ParisNakitaKejser
In my case, it's because I need only a single %s
, i missing values input.
就我而言,这是因为我只需要一个%s
,我缺少值输入。
回答by Victor Choy
I encounter the error as well,
我也遇到这个错误,
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")
elif len(name1) > len(name2):
print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
print ("{0} is longer than {1}".format(name2, name1))
But list args work well.
但是 list args 效果很好。
I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2']
will work.
我使用 mysqlclient python 库。lib 看起来不接受元组参数。像传递列表参数一样['arg1', 'arg2']
会起作用。
回答by Trevor Benson
There is a combination of issues as pointed out in a few of the other answers.
正如其他一些答案中指出的那样,存在一系列问题。
- As pointed out by nneonneo you are mixing different String Formatting methods.
- As pointed out by GuyP your indentation is off as well.
- 正如 nneonneo 所指出的,您正在混合不同的字符串格式方法。
- 正如 GuyP 所指出的,您的缩进也已关闭。
I've provided both the example of .format as well as passing tuples to the argument specifier of %s. In both cases the indentation has been fixed so greater/less than checks are outside of when length matches. Also changed subsequent if statements to elif's so they only run if the prior same level statement was False.
我已经提供了 .format 的例子以及将元组传递给 %s 的参数说明符。在这两种情况下,缩进都已修复,因此在长度匹配时大于/小于检查。还将后续的 if 语句更改为 elif,因此它们仅在先前的同一级别语句为 False 时才运行。
String Formatting with .format
使用 .format 进行字符串格式化
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")
elif len(name1) > len(name2):
print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
print ("%s is longer than %s" % (name2, name1))
String Formatting with %s and a tuple
使用 %s 和元组进行字符串格式化
"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)
回答by Vinay Kumar
django raw sql query in view
查看 django 原始 sql 查询
class VehicleDamage(models.Model):
requestdate = models.DateTimeField("requestdate")
vendor_name = models.CharField("vendor_name", max_length=50)
class Meta:
managed=False
models.py
模型.py
def location_damageReports(request):
#static date for testing
date_from = '2019-11-01'
date_to = '2019-21-01'
vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
data={"data": damage_report.data}
return HttpResponse(json.dumps(data), content_type="application/json")
views.py
视图.py
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
Note: using python 3.5 and django 1.11
注意:使用 python 3.5 和 django 1.11
回答by Shani
In python 3.7 and above there is a new and easy way. here is the syntax:
在 python 3.7 及更高版本中,有一种新的简单方法。这是语法:
Hello, Eric. You are 74.
OutPut:
输出:
x = (f"{id}", f"{name}", f"{age}")
print(x)
回答by Neel0507
For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.
对我来说,由于我在单个打印调用中存储了许多值,因此解决方案是创建一个单独的变量来将数据存储为元组,然后调用打印函数。
##代码##