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

该程序应采用两个名称,如果它们的长度相同,则应检查它们是否相同。如果是相同的单词,则将显示“名称相同”。如果它们的长度相同但字母不同,则会显示“名称不同但长度相同”。我有问题的部分在底部的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

任何建议,高度赞赏。

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.


回答 0

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

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

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

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)

回答 1

错误在于您的字符串格式。

使用’%’运算符使用传统字符串格式的正确方法是使用printf样式的格式字符串(此处的Python文档:http : //docs.python.org/2/library/string.html#format-字符串语法):

"'%s' is longer than '%s'" % (name1, name2)

但是,’%’运算符将来可能会被弃用。新的PEP 3101做事方式是这样的:

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

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

"'%s' is longer than '%s'" % (name1, name2)

However, the ‘%’ operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:

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

回答 2

对我来说,此错误是在我试图将元组传递给字符串格式方法时引起的。

我从这个问题/答案中找到了解决方案

从链接中复制并粘贴正确答案(“不做我的工作”)

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

用感兴趣的元组作为唯一项(即(tutuple)部分)制作单例元组是这里的关键。

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

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.


回答 3

就我而言,这是因为我只需要一个%s,我就缺少值输入。

In my case, it’s because I need only a single %s, i missing values input.


回答 4

除了其他两个答案,我认为缩进在最后两个条件下也是不正确的。条件是一个名字要长于另一个名字,并且它们必须以“ elif”开头且没有缩进。如果将其放在第一个条件下(通过从边缘开始给它四个缩进),则最终会导致矛盾,因为名称的长度不能同时相等且不同。

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

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.

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

回答 5

其他一些答案中也指出了很多问题。

  1. 正如nneonneo所指出的,您正在混合使用不同的字符串格式化方法。
  2. 正如GuyP指出的那样,您的缩进也已关闭。

我既提供了.format的示例,也提供了将元组传递给%s的参数说明符的方法。在这两种情况下,缩进均已固定,因此长度匹配时大于/小于检查范围。也将随后的if语句更改为elif,以便仅在先前的同一级别语句为False时才运行。

使用.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 ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

使用%s和元组进行字符串格式化

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

There is a combination of issues as pointed out in a few of the other answers.

  1. As pointed out by nneonneo you are mixing different String Formatting methods.
  2. As pointed out by GuyP your indentation is off as well.

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.

String Formatting with .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 ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

String Formatting with %s and a tuple

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

回答 6

在python 3.7及更高版本中,有一种新的简便方法。语法如下:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

输出:

Hello, Eric. You are 74.

In python 3.7 and above there is a new and easy way. here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

OutPut:

Hello, Eric. You are 74.

回答 7

我也遇到错误

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

但是列表参数工作良好。

我使用mysqlclient python lib。lib似乎不接受元组args。像这样传递列表参数['arg1', 'arg2'] 将起作用。

I encounter the error as well,

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

But list args work well.

I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2'] will work.


回答 8

Django原始SQL查询视图

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.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")

注意:使用python 3.5和Django 1.11

django raw sql query in view

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.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")

Note: using python 3.5 and django 1.11


回答 9

对我来说,因为我在一个打印调用中存储了许多值,所以解决方案是创建一个单独的变量以将数据存储为元组,然后调用打印函数。

x = (f"{id}", f"{name}", f"{age}")
print(x) 

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.

x = (f"{id}", f"{name}", f"{age}")
print(x) 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。