TypeError: not all arguments converted during string formatting python

PythonStringPython 3.xTypeerrorOutput Formatting

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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)

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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

Solution 6 - Python

In python 3.7 and above there is a new and easy way. It is called f-strings. Here is the syntax:

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

Output:

Hello, Eric. You are 74.

Solution 7 - Python

Keep in mind this error could also be caused by forgetting to reference the variable

"this is a comment" % comment #ERROR

instead of

"this is a comment: %s" % comment

Solution 8 - Python

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

Solution 9 - Python

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) 

Solution 10 - Python

Most Easy way typecast string number to integer

number=89
number=int(89)

Solution 11 - Python

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.

Solution 12 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2652300View Question on Stackoverflow
Solution 1 - PythonnneonneoView Answer on Stackoverflow
Solution 2 - PythonleonhView Answer on Stackoverflow
Solution 3 - PythonNick BradyView Answer on Stackoverflow
Solution 4 - PythonParisNakitaKejserView Answer on Stackoverflow
Solution 5 - PythonGuyPView Answer on Stackoverflow
Solution 6 - PythonTahir MusharrafView Answer on Stackoverflow
Solution 7 - PythonMarioView Answer on Stackoverflow
Solution 8 - PythonTrevor BensonView Answer on Stackoverflow
Solution 9 - PythonNeel0507View Answer on Stackoverflow
Solution 10 - Pythonsameer_nubiaView Answer on Stackoverflow
Solution 11 - PythonVictor ChoyView Answer on Stackoverflow
Solution 12 - PythonVinay KumarView Answer on Stackoverflow