Меню

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

pppery's user avatar

pppery

3,63020 gold badges31 silver badges44 bronze badges

asked Aug 5, 2013 at 8:15

user2652300's user avatar

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)

answered Aug 5, 2013 at 8:19

nneonneo's user avatar

nneonneonneonneo

168k35 gold badges299 silver badges372 bronze badges

2

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.

Community's user avatar

answered May 3, 2016 at 22:14

Nick Brady's user avatar

Nick BradyNick Brady

5,7441 gold badge44 silver badges68 bronze badges

1

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

answered Nov 26, 2013 at 7:27

GuyP's user avatar

GuyPGuyP

611 silver badge2 bronze badges

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

answered Apr 15, 2021 at 7:17

Mario's user avatar

MarioMario

1211 silver badge12 bronze badges

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.

Community's user avatar

answered Oct 23, 2019 at 13:02

Tahir Musharraf's user avatar

1

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) 

azro's user avatar

azro

51.4k7 gold badges35 silver badges67 bronze badges

answered Dec 13, 2019 at 14:50

Neel0507's user avatar

Neel0507Neel0507

1,0862 gold badges10 silver badges17 bronze badges

Most Easy way typecast string number to integer

number=89
number=int(89)

answered Aug 1, 2020 at 14:03

sameer_nubia's user avatar

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.

answered Feb 19, 2018 at 13:29

Victor Choy's user avatar

Victor ChoyVictor Choy

3,93026 silver badges33 bronze badges

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

pppery's user avatar

pppery

3,63020 gold badges31 silver badges44 bronze badges

asked Aug 5, 2013 at 8:15

user2652300's user avatar

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)

answered Aug 5, 2013 at 8:19

nneonneo's user avatar

nneonneonneonneo

168k35 gold badges299 silver badges372 bronze badges

2

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.

Community's user avatar

answered May 3, 2016 at 22:14

Nick Brady's user avatar

Nick BradyNick Brady

5,7441 gold badge44 silver badges68 bronze badges

1

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

answered Nov 26, 2013 at 7:27

GuyP's user avatar

GuyPGuyP

611 silver badge2 bronze badges

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

answered Apr 15, 2021 at 7:17

Mario's user avatar

MarioMario

1211 silver badge12 bronze badges

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.

Community's user avatar

answered Oct 23, 2019 at 13:02

Tahir Musharraf's user avatar

1

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) 

azro's user avatar

azro

51.4k7 gold badges35 silver badges67 bronze badges

answered Dec 13, 2019 at 14:50

Neel0507's user avatar

Neel0507Neel0507

1,0862 gold badges10 silver badges17 bronze badges

Most Easy way typecast string number to integer

number=89
number=int(89)

answered Aug 1, 2020 at 14:03

sameer_nubia's user avatar

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.

answered Feb 19, 2018 at 13:29

Victor Choy's user avatar

Victor ChoyVictor Choy

3,93026 silver badges33 bronze badges

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

pppery's user avatar

pppery

3,63020 gold badges31 silver badges44 bronze badges

asked Aug 5, 2013 at 8:15

user2652300's user avatar

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)

answered Aug 5, 2013 at 8:19

nneonneo's user avatar

nneonneonneonneo

168k35 gold badges299 silver badges372 bronze badges

2

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.

Community's user avatar

answered May 3, 2016 at 22:14

Nick Brady's user avatar

Nick BradyNick Brady

5,7441 gold badge44 silver badges68 bronze badges

1

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

answered Nov 26, 2013 at 7:27

GuyP's user avatar

GuyPGuyP

611 silver badge2 bronze badges

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

answered Apr 15, 2021 at 7:17

Mario's user avatar

MarioMario

1211 silver badge12 bronze badges

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.

Community's user avatar

answered Oct 23, 2019 at 13:02

Tahir Musharraf's user avatar

1

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) 

azro's user avatar

azro

51.4k7 gold badges35 silver badges67 bronze badges

answered Dec 13, 2019 at 14:50

Neel0507's user avatar

Neel0507Neel0507

1,0862 gold badges10 silver badges17 bronze badges

Most Easy way typecast string number to integer

number=89
number=int(89)

answered Aug 1, 2020 at 14:03

sameer_nubia's user avatar

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.

answered Feb 19, 2018 at 13:29

Victor Choy's user avatar

Victor ChoyVictor Choy

3,93026 silver badges33 bronze badges

Table of Contents
Hide
  1. Resolving typeerror: not all arguments converted during string formatting
  2. Applying incorrect format Specifier 
  3. Incorrect formatting and substitution of values during string interpolation 
  4. Mixing different types of format specifiers

In Python, typeerror: not all arguments converted during string formatting occurs mainly in 3 different cases.

  1. Applying incorrect format Specifier 
  2. Incorrect formatting and substitution of values during string interpolation 
  3. Mixing different types of format specifiers

In Python, TypeError occurs if you perform an operation or use a function on an object of a different type. Let us look at each of the scenarios in depth with examples and solutions to these issues.

Applying incorrect format Specifier 

If you use the percentage symbol (%) on a string, it is used for formatting, and if you are using it on an integer, it is for calculating the modulo.

If you look at the below code to check odd or even numbers, we accept an input number in the form of string and perform modulus operation (%) on string variable. Since it cannot perform a division of string and get the reminder, Python will throw not all arguments converted during string formatting error. 

# Check even or odd scenario
number= (input("Enter a Number: "))
if(number % 2):
    print("Given number is odd")
else:
    print("Given number is even")

# Output 
Enter a Number: 5
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 3, in <module>
    if(number % 2):
TypeError: not all arguments converted during string formatting

Solution – The best way to resolve this issue is to convert the number into an integer or floating-point if we perform a modulus operation.

# Check even or odd scenario
number= (input("Enter a Number: "))
if(int(number) % 2):
    print("Given number is odd")
else:
    print("Given number is even")

# Output
Enter a Number: 5
Given number is odd

Incorrect formatting and substitution of values during string interpolation 

In this example, we are performing a string interpolation by substituting the values to the string specifiers. If you notice clearly, we are passing an extra value country without providing the specifier for which Python will throw a  not all arguments converted during string formatting error.

name ="Jack"
age =20
country="India"

print("Student %s is %s years old "%(name,age,country))

# Output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 5, in <module>
    print("Student %s is %s years old "%(name,age,country))
TypeError: not all arguments converted during string formatting

Solution – You could resolve the issue by matching the number of specifiers and values, as shown above.

name ="Jack"
age =20
country="India"

print("Student %s is %s years old and he is from %s "%(name,age,country))

# Output
Student Jack is 20 years old and he is from India 

Mixing different types of format specifiers

The major issue in the below code is mixing up two different types of string formatting. We have used {} and % operators to perform string interpolation, so Python will throw TypeError in this case.

# Print Name and age of Student
name = input("Enter name : ")
age = input("Enter Age  : ")

# Print Name and Age of user
print("Student name is '{0}'and Age is '{1}'"% name, age)

# Output
Enter name : Chandler
Enter Age  : 22
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 6, in <module>
    print("Student name is '{0}'and Age is '{1}'"% name, age)
TypeError: not all arguments converted during string formatting

Solution –   The % operator will be soon deprecated, instead use the modern approach {} with .format() method as shown below.

The .format() method replaces the values of {} with the values specifed in .format() in the same order mentioned.


# Print Name and age of Student
name = input("Enter name : ")
age = input("Enter Age  : ")

# Print Name and Age of user
print("Student name is '{0}'and Age is '{1}'".format(name, age))

# Output
Enter name : Chandler
Enter Age  : 22
Student name is 'Chandler'and Age is '22'

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

The TypeError: not all arguments converted during string formatting error occurs if no format specifier is available or the number of format specifiers is less than the number of values passed. The error is caused when Python does not convert all arguments to the string format operation. Also, this python error TypeError: not all arguments converted during string formatting occurs when you are mixing different format specifiers. The percentage % formatting uses % codes. The new-style {} formatting uses {} codes and the format() method.

The string format specifyer is used to dynamically replace the value in the string. The string uses percent (“%”) to specify the formats. The new string format specifyer uses the curly braces. The number of format specified and the number of values passed should be same.

If the new and old string formats are mixed, the python interpreter will throw this error “TypeError: not all arguments converted during string formatting. If both are mixed, python interpreter can not match the format specifiers with the values passed in the string.

Exception

The type error stack trace will be shown as below

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x % y
TypeError: not all arguments converted during string formatting
[Finished in 0.1s with exit code 1]

Root Cause

This type error is due to the following reasons.

  • There is no format specifier.
  • The number of format specifier is less than the number of values passed
  • The two string format specifiers are mixed.

Solution 1

If the string does not have format specifyer and contains a number, then the percent “%” is used as a mod operation. The mathematical mod will be performed with two numbers and the remainder will be returned. The string format specifier will not apply in this case. The error “TypeError: not all arguments converted during string formatting” will be resolved on this.

Program

x = "10"
y = 5
print x % y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x % y
TypeError: not all arguments converted during string formatting
[Finished in 0.1s with exit code 1]

Solution

x = "10"
y = 5
print int(x) % y

Output

0
[Finished in 0.1s]

Solution 2

The string does not have any format specifier and the value is passed to be replaced, so the python interpreter can not replace the value. The format specifier must be added in the string. The python interpreter will match the format specifier with the passed values. So, this will resolve the type error.

Program

x = "Your cost is "
y = 5
print x % y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x % y
TypeError: not all arguments converted during string formatting
[Finished in 0.0s with exit code 1]

Solution

x = "Your cost is %s"
y = 5
print x % y

Output

Your cost is 5
[Finished in 0.0s]

Solution 3

In python, if the number of format specifier is less than the value passed, the python interpreter can not replace all the values in the string format. The missing format specifier must be added in the string. This will resolve the type error.

Program

x = 5
y = 10
print "The values are %s" % (x, y)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print "The values are %s" % (x, y)
TypeError: not all arguments converted during string formatting
[Finished in 0.1s with exit code 1]

Solution

x = 5
y = 10
print "The values are %s %s" % (x, y)

Output

The values are 5 10
[Finished in 0.0s]

Solution 4

In python, if the two string formats are mixed in the string, the python interpreter can not replace all the values in the string format. The string should be followed by any one of the format specifiers to replace values. Convert the string to a single format. This is going to solve the type error.

Program

x = 5
y = 10
print "The values are {0} {1}" % (x, y)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print "The values are {0} {1}" % (x, y)
TypeError: not all arguments converted during string formatting
[Finished in 0.0s with exit code 1]

Solution

x = 5
y = 10
print "The values are %s %s" % (x, y)

Output

The values are 5 10
[Finished in 0.0s]

Solution 5

In python, if the two string formats are mixed in the string, the python interpreter can not replace all the values in the string format. The string should be followed by any one of the format specifiers to replace values. Convert the string to a single format. This is going to solve the type error.

Program

x = 5
y = 10
print "The values are {0} {1}" % (x, y)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print "The values are {0} {1}" % (x, y)
TypeError: not all arguments converted during string formatting
[Finished in 0.0s with exit code 1]

Solution

x = 5
y = 10
print "The values are {0} {1}".format(x, y)

Output

The values are 5 10
[Finished in 0.0s]

Python is a stickler for the rules. One of the main features of the Python language keeps you in check so that your programs work in the way that you intend. You may encounter an error saying “not all arguments converted during string formatting” when you’re working with strings.

In this guide, we talk about this error and why it pops up. We walk through two common scenarios where this error is raised to help you solve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Without further ado, let’s begin!

The Problem: typeerror: not all arguments converted during string formatting

A TypeError is a type of error that tells us we are performing a task that cannot be executed on a value of a certain type. In this case, our type error relates to a string value.

Python offers a number of ways that you can format strings. This allows you to insert values into strings or concatenate values to the end of a string.

Two of the most common ways of formatting strings are:

  • Using the % operator (old-style)
  • Using the {} operator with the .format() function

When you try to use both of these syntaxes together, an error is raised.

Example: Mixing String Formatting Rules

Let’s write a program that calculates a 5% price increase on a product sold at a bakery.

We start by collecting two pieces of information from the user: the name of the product and the price of the product. We do this using an input() statement:

name = input("Enter the name of the product: ")
price = input("Enter the price of the product: ")

Next, we calculate the new price of the product by multiplying the value of “price” by 1.05. This represents a 5% price increase:

increase = round(float(price) * 1.05, 2)

We round the value of “increase” to two decimal places using a round() statement. Finally, use string formatting to print out the new price of the product to the console:

print("The new price of {} is ${}. " % name, str(increase))

This code adds the values of “name” and “increase” into our string. We convert “increase” to a string to merge it into our string. Before we convert the value, “increase” is a floating-point number. Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
	print("The new price of {} is {}" % name, str(discount))
TypeError: not all arguments converted during string formatting

It appears there is an error on the last line of our code.

The problem is we mixed up our string formatting syntax. We used the {} and % operators. These are used for two different types of string formatting.

To solve this problem, we replace the last line of our programming with either of the two following lines of code:

print("The new price of {} is ${}.".format(name, str(increase)))

print("The new price of %s is $%s." % (name, str(increase)))

The first line of code uses the .format() syntax. This replaces the values of {} with the values in the .format() statement in the order they are specified.

The second line of code uses the old-style % string formatting technique. The values “%s” is replaced with those that are enclosed in parenthesis after the % operator.

Let’s run our code again and see what happens:

Enter the name of the product: Babka
Enter the price of the product: 2.50
The new price of Babka is $2.62.

Our code successfully added our arguments into our string.

Example: Confusing the Modulo Operator

Python uses the percentage sign (%) to calculate modulo numbers and string formatting. Modulo numbers are the remainder left over after a division sum.

If you use the percentage sign on a string, it is used for formatting; if you use the percentage sign on a number, it is used to calculate the modulo. Hence, if a value is formatted as a string on which you want to perform a modulo calculation, an error is raised.

Take a look at a program that calculates whether a number is odd or even:

number = input("Please enter a number: ")
mod_calc = number % 2

if mod_calc == 0:
	print("This number is even.")
else:
	print("This number is odd.")

First, we ask the user to enter a number. We then use the modulo operator to calculate the remainder that is returned when “number” is divided by 2.

If the returning value by the modulo operator is equal to 0, the contents of our if statement execute. Otherwise, the contents of the else statement runs.

Let’s run our code:

Please enter a number: 7
Traceback (most recent call last):
  File "main.py", line 2, in <module>
	mod_calc = number % 2
TypeError: not all arguments converted during string formatting

Another TypeError. This error is raised because “number” is a string. The input() method returns a string. We need to convert “number” to a floating-point or an integer if we want to perform a modulo calculation.

We can convert “number” to a float by using the float() function:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

mod_calc = float(number) % 2

Let’s try to run our code again:

Please enter a number: 7
This number is odd.

Our code works!

Conclusion

The “not all arguments converted during string formatting” error is raised when Python does not add in all arguments to a string format operation. This happens if you mix up your string formatting syntax or if you try to perform a modulo operation on a string.

Now you’re ready to solve this common Python error like a professional software engineer!

  1. Causes and Solutions for TypeError: Not All Arguments Converted During String Formatting in Python
  2. Conclusion

Solve the TypeError: Not All Arguments Converted During String Formatting in Python

String formatting in Python can be done in various ways, and a modulo (%) operator is one such method. It is one of the oldest methods of string formatting in Python, and using it in the wrong way might cause the TypeError: not all arguments converted during string formatting to occur.

Not just that, many other reasons can cause the same. Let us learn more about this error and the possible solutions to fix it.

TypeError is a Python exception raised when we try to operate on unsupported object types. There are many scenarios where we can get this error, but in this article, we will look at the Python TypeError that occurs from the incorrect formatting of strings.

Without further ado, let us begin!

Causes and Solutions for TypeError: Not All Arguments Converted During String Formatting in Python

There are many reasons why the TypeError: not all arguments converted during string formatting might occur in Python. Let us discuss them one by one, along with the possible solutions.

Operations on the Wrong Data Type in Python

Look at the example given below. Here, we take the user’s age as input and then use the modulo operator (%).

The result is stored in the variable ans, which is then formatted to the string in the print statement. But when we run this code, we get the TypeError.

This happens because Python takes input in the form of a string. This means that the value 19 taken as the input is considered the str data type by Python.

But can we use a modulo operator (%) on a string? No, and hence, we get this error.

age = (input("Enter your age: "))
ans = age % 10
print("Your lucky number is:", ans)

Output:

Enter your age: 19
Traceback (most recent call last):
  File "<string>", line 2, in <module>
TypeError: not all arguments converted during string formatting

To fix this, we must take the input as an integer using the int() function. This is done below.

age = int(input("Enter your age: "))
ans = age % 10
print("Your lucky number is:", ans)

Output:

Enter your age: 19
Your lucky number is: 9

You can see that this time we get the desired output since the int() function converts the input to integer data type, and we can use the modulo operator (%) on it.

Absence of Format Specifier With the String Interpolation Operator in Python

This case is a little bit similar to the one we discussed above. Look at the example given below.

The output shows us that the error occurred in line 2. But can you guess why?

The answer is simple. We know that anything inside single or double quotes in Python is a string.

Here, the value 19 is enclosed in double quotes, which means that it is a string data type, and we cannot use the modulo operator (%) on it.

age = "19"
if(age%10):
    print("Your age is a lucky number")

Output:

Traceback (most recent call last):
  File "<string>", line 2, in <module>
TypeError: not all arguments converted during string formatting

To rectify this, we will use the int() format specifier, as done below.

age = "19"
if(int(age)%10):
    print("Your age is a lucky number")

Output:

Your age is a lucky number

This time the code runs fine.

Unequal Number of Format Specifiers and Values in Python

We know that we put as many format specifiers during string formatting as the number of values to be formatted. But what if there are more or fewer values than the number of format specifiers specified inside the string?

Look at this code. Here, we have three variables and want to insert only two of them into the string.

But when we pass the arguments in the print statement, we pass all three of them, which no doubt results in the TypeError.

lead_actor = "Harry Potter"
co_actor = "Ron Weasley"
actress = "Hermione Granger"

print("The males in the main role were: %s and %s." %(lead_actor,co_actor, actress ))

Output:

Traceback (most recent call last):
  File "<string>", line 5, in <module>
TypeError: not all arguments converted during string formatting

Let us remove the last variable, actress, from the list of arguments and then re-run this program.

lead_actor = "Harry Potter"
co_actor = "Ron Weasley"
actress = "Hermione Granger"

print("The males in the main role were: %s and %s." %(lead_actor,co_actor))

Output:

The males in the main role were: Harry Potter and Ron Weasley.

You can see that this time the code runs fine because the number of format specifiers inside the string is equal to the number of variables passed as arguments.

Note that the format specifier to be used depends on the data type of the values, which in this case is %s as we are dealing with the string data type.

Use of Different Format Specifiers in the Same String in Python

We know that there are several ways in which we can format a string in Python, but once you choose a method, you have to follow only that method in a single string. In other words, you cannot mix different types of string formatting methods in a single statement because it will lead to the TypeError: not all arguments converted during string formatting.

Look at the code below to understand this concept better.

We are using placeholders({}) inside the string to format this string, but we do not pass the arguments as a tuple as we did earlier. Instead, one of the variables is preceded with a modulo operator (%) while the other one is not.

This is what leads to the TypeError.

lead_actor = "Harry Potter"
co_actor = "Ron Weasley"
actress = "Hermione Granger"

print("The males in the main role were: {0} and {1}." % lead_actor,co_actor)

Output:

Traceback (most recent call last):
  File "<string>", line 5, in <module>
TypeError: not all arguments converted during string formatting

To fix this, we can do two things.

  1. If you want to use placeholders({}) inside the string, then you must use the format() method with the dot (.) operator to pass the arguments. This is done below.

    lead_actor = "Harry Potter"
    co_actor = "Ron Weasley"
    actress = "Hermione Granger"
    
    print("The males in the main role were: {0} and {1}.".format(lead_actor, co_actor))
    

    Output:

    The males in the main role were: Harry Potter and Ron Weasley.
    

    ​You can see that this time the code runs fine.

  2. The other way could be to drop the use of placeholders({}) and use format specifiers in their place along with passing the arguments as a tuple preceded by the modulo operator (%). This is done as follows.

    lead_actor = "Harry Potter"
    co_actor = "Ron Weasley"
    actress = "Hermione Granger"
    
    print("The males in the main role were: %s and %s." % (lead_actor, co_actor))
    

    Output:

    The males in the main role were: Harry Potter and Ron Weasley.
    

    Note that the modulo operator (%) for formatting is an old-style while, on the other hand, the use of the placeholders with the .format() method is a new-style method of string formatting in Python.

This is it for this article. To learn more about string formatting in Python, refer to this documentation.

Conclusion

In this article, we talked about the various reasons that lead to TypeError: Not all arguments converted during string formatting in Python, along with the possible fixes.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Not all arguments converted during string formatting python ошибка
  • Not accessible ошибка принтера