Not all arguments converted during string formatting как исправить

введите сюда описание изображения

Учусь кодить на Питоне. Не знаю, что я сделал не так…

insolor's user avatar

insolor

45.7k16 золотых знаков54 серебряных знака95 бронзовых знаков

задан 20 мая 2018 в 6:58

TOTORO's user avatar

0

Таким кодом Python не понимает что это за тип переменной, которую вы ввели.
Попробуйте сменить код на x=int(input()).
Даже в самой ошибке сказано про string format

ответ дан 20 мая 2018 в 7:03

Pashok's user avatar

PashokPashok

1,1062 золотых знака15 серебряных знаков29 бронзовых знаков

Оператор % в Python работает по-разному в зависимости от типа объектов, к которым применяется:

  1. Дает остаток от деления, если применяется к числам: 3 % 2 = 1
  2. Для строк применяется как оператор форматирования:
    "Результат равен %s попугаям" % 48 превратится в "Результат равен 48 попугаям"

Вы применяете оператор к строкам (функция input() возвращает строки), поэтому Python пытается применить второй вариант. Но т.к. в первой строке нет “маркеров” для подстановки (как %s внутри строки в примере выше), то получаете ошибку “не все аргументы были преобразованы во время форматирования”.

В вашем случае просто нужно преобразовать введенные данные в числа.

ответ дан 20 мая 2018 в 10:08

insolor's user avatar

insolorinsolor

45.7k16 золотых знаков54 серебряных знака95 бронзовых знаков

Table of Contents

  • Overview
  • ❑ What is TypeError in Python?
  • ❑ How to Fix Type Error: not all arguments converted during string formatting in Python?
    • 💡 Scenario 1: No Format Specifier With The String Interpolation Operator
      • ☞ Method 1: Using format() function
      • ☞ Method 2: Using % Operator (String Interpolation Operator)
    • 💡 Scenario 2: Incorrect Usage of % Operator
    • 💡 Scenario 3: Missing Format Specifiers While Using % for String Formatting
  • Conclusion

Overview

Problem Formulation: How to fix Type Error-Not all arguments converted during string formatting in Python?

Example: Consider the following program that checks if a number is even or odd.

x = input(‘Enter A Number: ‘)

if x % 2 == 0:

    print(x, “is an Even Number!”)

else:

    print(x, “is a Odd Number!”)

Output:

Enter A Number: 11
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in <module>
if x % 2 == 0:
TypeError: not all arguments converted during string formatting

Confused! 🤔 No worries, in this article, you will understand the reasons behind such errors with the help of numerous examples and scenarios. Most importantly, you will learn how to deal with it. So without further delay, let us begin our discussion.

❑ What is TypeError in Python?

Python raises a Type Error Exception when you try to perform an operation on two different/unrelated types of operands or objects. Thus, you will encounter a TypeError when you try to call a function or use an operator on something of the incorrect type.

Example:

Output:

Traceback (most recent call last):
File “main.py”, line 1, in
print(‘Java’+2+’Blog’)
TypeError: can only concatenate str (not “int”) to str

In the above example, the plus operator (+) was expected between two numeric parameters or two strings, i.e., objects of the same type. However, we tried to concatenate a string and a numeric value which lead to the occurrence of TypeError: can only concatenate str (not "int") to str.

Solution: To avoid the above TypeError, you must ensure that you concatenate objects of the same type (str in this case.)

print(‘Java’+‘2’+‘Blog’)

# Output: Java2Blog

This brings us to our next question 👇

❑ How to Fix Type Error: not all arguments converted during string formatting in Python?

Let’s have a look at few examples/scenarios to understand how we can resolve Type Error: not all arguments converted during string formatting in our code.

💡 Scenario 1: No Format Specifier With The String Interpolation Operator

➣ The most common ways of formatting strings in Python are:

  • The old style of string formatting i.e. using the % operator.
  • By using {} operator with the .format () function.

⚠️ Note: You should not use both together. When you mix both the styles of string formatting, Python throws Type Error: not all arguments converted during string formatting.

Example:

f_name = input(“Enter your first name: “)

l_name = input(“Enter your last name: “)

print(“Your Name: {} {}” % f_name, l_name)

Output:

Enter your first name: Shubham
Enter your last name: Sayon
Traceback (most recent call last):
File “main.py”, line 3, in <module>
print(“Your Name: {} {}” % f_name, l_name)
TypeError: not all arguments converted during string formatting

Explanation: In the above example, we tried to mix both the styles of string formatting which lead to the occurrence of TypeError.

Solution: To overcome this problem, you must stick to a single style of string formatting.

Hence, use one of the following types as show in the solutions below:

Method 1: Using format() function

f_name = input(“Enter your first name: “)

l_name = input(“Enter your last name: “)

print(“Your Name: {} {}”.format(f_name, l_name)) # new way

Output:

Enter your first name: Shubham
Enter your last name: Sayon
Your Name: Shubham Sayon

Method 2: Using % Operator (String Interpolation Operator)

f_name = input(“Enter your first name: “)

l_name = input(“Enter your last name: “)

print(“Your Name: %s %s”%(f_name,l_name)) # old way

Output:

Enter your first name: Shubham
Enter your last name: Sayon
Your Name: Shubham Sayon

💡 Scenario 2: Incorrect Usage of % Operator

In Python % operator can be used in two ways:

  • Used to find the modulus
    • When used with numbers / numeric calculations.
  • Used for string formatting
    • When used with a string within the print statement.

Now, if you confuse between the two usages and try to find the modulus of a string input/value, you will encounter a TypeError.

Example: Program to check leap year.

year = input(‘Enter the year: ‘)

if (year % 4) == 0:

    if (year % 100) == 0:

        if (year % 400) == 0:

            print(“{0} is a leap year”.format(year))

        else:

            print(“{0} is not a leap year”.format(year))

    else:

        print(“{0} is a leap year”.format(year))

else:

    print(“{0} is not a leap year”.format(year))

Output:

Enter the year: 2004
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in <module>
if (year % 4) == 0:
TypeError: not all arguments converted during string formatting

Explanation: We tried to use the % operator on a string input in the second line of our code. This lead to the occurrence of the TypeError.

Solution: Ensure that the user input is an integer value by using the int() method.

year = int(input(‘Enter the year: ‘))

if (year % 4) == 0:

    if (year % 100) == 0:

        if (year % 400) == 0:

            print(“{0} is a leap year”.format(year))

        else:

            print(“{0} is not a leap year”.format(year))

    else:

        print(“{0} is a leap year”.format(year))

else:

    print(“{0} is not a leap year”.format(year))

Output:

Enter the year: 2008
2008 is a leap year

💡 Scenario 3: Missing Format Specifiers While Using % for String Formatting

When the number of format specifiers present is less than than number of values passed, it leads to the occurrence of TypeError: not all arguments converted during string formatting.

Example:

print(“%d+%d=25”%(10,15,25))

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 1, in <module>
print(“%d+%d=25″%(6,4,15))
TypeError: not all arguments converted during string formatting

Solution: The obvious solution to this problem is to use an equal number of values and format specifiers. Another approach to avoid this problem is to use the .format() method for string formatting.

.format () ensures that only the exact number of values as the number of {} specifiers in the string expression is passed, and the extra values are ignored.

print(“{}+{}=25”.format(10,15,25))

Output:

10+15=25

Conclusion

So, in this article, you learned about TypeError: not all arguments converted during string formatting. And now, you are all set to solve this irritating bug like a Pro!

Read more here: [Solved] TypeError: Can’t Multiply Sequence by non-int of Type ‘float’ In Python?

Please stay tuned and subscribe for more interesting articles.

  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.

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.

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!

Добавить комментарий