Что означает ошибка TypeError: can only concatenate str (not “int”) to str
Это значит, что вы пытаетесь сложить строки с числами
Это значит, что вы пытаетесь сложить строки с числами
Программист освоил JavaScript и начал изучать Python. Чтобы освоиться в языке, он переносит проекты с одного языка на другой — убирает точки с запятой, добавляет отступы и меняет команды одного языка на такие же команды из другого языка.
Один из фрагментов его кода после перевода в Python выглядит так:
# зарплата в месяц
month = 14200
# плата за ЖКХ
regular_cost = 5800
# функция, которая считает и возвращает долю ЖКХ в бюджете
def calculate(budget,base):
message = 'На коммунальные платежи уходит ' + base + 'р. - это ' + base/budget*100 + ' процентов от ежемесячного бюджета'
return message
# отправляем в функцию переменные и выводим результат на экран
print(calculate(month,regular_cost))
Но после запуска программист получает ошибку:
❌ TypeError: can only concatenate str (not “int”) to str
Странно, но в JavaScript всё работало, почему же здесь код сломался?
Что это значит: компилятор не смог соединить строки и числа, поэтому выдал ошибку.
Когда встречается: в языках со строгой типизацией, например в Python, когда у всех переменных в выражении должен быть один и тот же тип данных. А вот в JavaScript, который изучал программист до этого, типизация нестрогая, и компилятор сам мог привести все части выражения к одному типу.
Что делать с ошибкой TypeError: can only concatenate str (not “int”) to str
Раз это проблема строгой типизации, то для исправления этой ошибки нужно просто привести все части к одному типу.
В нашем случае мы хотим получить на выходе строку, поэтому все слагаемые должны быть строкового типа. Но base
и base/budget*100
— это числа, поэтому просто так их сложить со строками не получится. Чтобы выйти из ситуации, явно преобразуем их в строки командой str()
:
message = 'На коммунальные платежи уходит ' + str(base) + 'р. - это ' + str(base/budget*100) + ' процентов от ежемесячного бюджета'
Команда str()
делает так, что всё внутри неё приводится к строке и она отдаёт дальше строку. В итоге операция склейки строк проходит как ожидаемо: строка к строке даёт строку. Нет повода для беспокойства.
Вёрстка:
Кирилл Климентьев
- I decided to make some kind of secret code for testing purposes with Unicode.
- I’ve done that by adding numbers to Unicode so it would be kind of secret.
- I’ve been getting this error, but I don’t know how to solve it.
- Is there any solution?
Original Code
message = input("Enter a message you want to be revealed: ")
secret_string = ""
for char in message:
secret_string += str(chr(char + 7429146))
print("Revealed", secret_string)
q = input("")
Original Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-182-49ece294a581> in <module>
2 secret_string = ""
3 for char in message:
----> 4 secret_string += str(chr(char + 7429146))
5 print("Revealed", secret_string)
6 q = input("")
TypeError: can only concatenate str (not "int") to str
Updated code
while True:
try:
message = int(input("Enter a message you want to be decrypt: "))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
secret_string += chr(ord(char - str(742146)))
print("Decrypted", secret_string)
q = input("")
asked Jul 9, 2018 at 19:13
0
Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str…
So for example the code below throw an error:
print( "Alireza" + 1980)
like this:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str
To solve the issue, just add str to your number or value like:
print( "Alireza" + str(1980))
And the result as:
Alireza1980
answered Aug 12, 2018 at 2:39
AlirezaAlireza
99.1k27 gold badges266 silver badges171 bronze badges
Use f-strings to resolve the TypeError
- f-Strings: A New and Improved Way to Format Strings in Python
- PEP 498 – Literal String Interpolation
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with an f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
- The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
- Convert the string to an
int
. - This scenario is specific to this question
- Convert the string to an
- When iterating, it’s important to be aware of the
type
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
Note
- The preceding part of the answer addresses the
TypeError
shown in the question title, which is why people seem to be coming to this question. - However, this doesn’t resolve the issue in relation to the example provided by the OP, which is addressed below.
Original Code Issues
TypeError
is caused becausetype(message) → str
.- The code iterates each character and attempts to add
char
, astr
type, to anint
- That issue can be resolved by converting
char
to anint
- As the code is presented,
secret_string
needs to be initialized with0
instead of""
.
- The code iterates each character and attempts to add
- The code also results in a
ValueError: chr() arg not in range(0x110000)
because7429146
is out of range forchr()
.- Resolved by using a smaller number
- The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
Updated Code Issues
message
is now anint
type, sofor char in message:
causesTypeError: 'int' object is not iterable
message
is converted toint
to make sure theinput
is anint
.- Set the type with
str()
- Only convert
value
to Unicode withchr
- Don’t use
ord
- Don’t use
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ✙✙✙
Enter a message you want to be decrypt: 100
Decrypted ✑✐✐
answered Jun 19, 2020 at 18:49
Trenton McKinneyTrenton McKinney
54k32 gold badges137 silver badges149 bronze badges
instead of using ” + ” operator
print( "Alireza" + 1980)
Use comma ” , ” operator
print( "Alireza" , 1980)
answered Oct 13, 2018 at 7:07
3
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
answered Mar 20, 2019 at 16:20
Problem is you are doing the following
str(chr(char + 7429146))
where char is a string. You cannot add a int with a string. this will cause that error
maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112
answered Jul 9, 2018 at 19:19
rawwarrawwar
4,8248 gold badges32 silver badges56 bronze badges
0
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord()
converts the character to its Unicode integer equivalent. chr()
then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111
answered Jul 9, 2018 at 19:24
Tori HarrisTori Harris
5532 gold badges7 silver badges20 bronze badges
0
TypeError: can only concatenate str (not "int") to str
This error occurs when you try adding (concatenating) an integer to a string. This error happens most commonly when trying to print an integer variable or writing information to a file. You would also get this error when adding a float or list to a string or other data types.
Types in Python have various associated methods, which restrict what you can or can’t do with that specific data type. Some of the main types which you may have encountered so far are strings, integers, and floats.
In this lesson, we’ll focus on strings and considering some examples where you may need to combine numbers with your string to display information effectively.
In this example, let’s say you’ve just discovered the //
operator, which divides the first operand by the second and rounds the result down to the nearest integer — also known as floor division. You’re interested in finding out the results given by this operator for various numbers, so you write the following script:
result = 4961 // 342
print('The result is : ' + result)
Out:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-4458afcb9bfc> in <module>
1 result = 4961 // 342
2
----> 3 print('The result is : ' + result)
TypeError: can only concatenate str (not "int") to str
The script gets through the calculations but fails when we try to combine our result with the text in result_string
. This failure occurs because the concatenate operator (+) for strings in Python doesn’t know how to comvert convert numeric types to strings implicitly.
There are three straightforward solutions:
- Convert the integer variable to a string before concatenating
- Use a comma in the
print()
statement to concatenate - Use an
f''
string (f-string).
Each of these are demonstrated below.
result = 4961 // 342
# 1
print('The result is: ' + str(result))
# 2
print('The result is:', result)
# 3
print(f'The result is: {result}')
Out:
The result is: 14
The result is: 14
The result is: 14
In option one, by applying the str()
function to our result
variable, we converted the result
variable from an int
to a str
, converting from 14 to ’14’. Similarly, if we wanted to convert our variable back into an integer or a float instead, we could use the functions int()
or float()
to convert ’14’ to 14 or 14.0, respectively. The conversion from one type to another is called type casting.
Option two allows the print()
function to convert the result
to str
automatically.
Option three performs a conversion through the use of curly braces in an f-string.
This error can also be triggered by appending values from a collection-type object to a string. Lists, tuples, and dictionaries are all examples of collection types.
Imagine you’ve got a dictionary of employees at Company A, describing their position and salaries (in thousands). You’d like to create a script that iterates through the employees and prints off lines representing their jobs and salaries. This information could be displayed as follows:
salary_dict = {
'Junior Data Scientist' : 80,
'Senior Data Scientist' : 120,
'Lead Data Engineer' : 140,
}
for employee, salary in salary_dict.items():
print('Position: ' + employee + ' Salary: $' + salary + '000')
Out:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-0b430355c9a3> in <module>
6
7 for employee, salary in salary_dict.items():
----> 8 print('Position: ' + employee + ' Salary: $' + salary + '000')
TypeError: can only concatenate str (not "int") to str
Taking a look at the dictionary we’ve used, the keys are all in string format, so Python should have no problems concatenating the employee variable to the string. The error comes from the dictionary values being integers.
We could edit the dictionary and convert these values into strings manually, but we have other options at our disposal.
salary_dict = {
'Junior Data Scientist' : 80,
'Senior Data Scientist' : 120,
'Lead Data Engineer' : 140,
}
for employee, salary in salary_dict.items():
print(f'Position: {employee}, Salary: ${salary}000')
Out:
Position: Junior Data Scientist, Salary: $80000
Position: Senior Data Scientist, Salary: $120000
Position: Lead Data Engineer, Salary: $140000
As seen in the previous solution, the f-string lets us insert variables into strings without explicit conversion to str
. Even though we used an f-string here, any of the other options from above could’ve worked.
As mentioned previously, this error can frequently occur when writing data to a file. An excellent example is writing comma-separated-values (CSV) files for data analysis (much easier in pandas).
You could do this by generating all your values in a context manager and then writing them to the CSV file as you go. A script for executing this is shown below, with the script generating a CSV file called x_power_values.csv, which contains values for x, x squared, and x cubed.
with open('x_power_values.csv', 'w') as f:
# Write CSV header row
f.write('x,x_squared,x_cubedn')
for x in range(1,1001):
x_squared = x**2
x_cubed = x**3
file_row = str(x) + ',' + x_squared + ',' + x_cubed + 'n'
f.write(file_row)
Out:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-0311bccc0432> in <module>
7 x_squared = x**2
8 x_cubed = x**3
----> 9 file_row = str(x) + ',' + x_squared + ',' + x_cubed + 'n'
10 f.write(file_row)
TypeError: can only concatenate str (not "int") to str
Although we have converted x
from an integer to a string, x_squared
and x_cubed
are still integers as these get generated before converting x
. We can quickly fix this using one of the methods already mentioned above:
with open('x_power_values.csv', 'w') as f:
# Write CSV header row
f.write('x,x_squared,x_cubedn')
for x in range(1,1001):
x_squared = x**2
x_cubed = x**3
file_row = f'{x},{x_squared},{x_cubed}n'
f.write(file_row)
In this solution, we’ve utilized an f-string again. Now that Python can concatenate x_squared
and x_cubed
to the file_row
string, the CSV file can be generated successfully by the script. In a pandas DataFrame, our CSV file would look like this:
x x_squared x_cubed 0 1 1 1 1 2 4 8 2 3 9 27 3 4 16 64 4 5 25 125 .. ... ... ... 999 1000 1000000 1000000000
This error occurs when Python tries to combine conflicting data types. In this scenario, the issue was triggered by attempting to concatenate strings and integers, but a wide range of different types can cause this problem.
In many situations, we can solve the problem by converting a variable to the string type using the str()
function, using comma-separated arguments to print()
, or by using an f-string to handle the concatenation for us.
Your Python program crashed and displayed a traceback like this one:
Traceback (most recent call last):
File "copyright.py", line 4, in <module>
statement = "Copyright " + year
TypeError: can only concatenate str (not "int") to str
Or maybe you saw a variation on that message:
Traceback (most recent call last):
File "names.py", line 3, in <module>
print("Hello" + names)
TypeError: can only concatenate str (not "list") to str
Or you may have seen a different error message that mentions +
and int
and str
:
Traceback (most recent call last):
File "add.py", line 5, in <module>
print(start + amount)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
What do these mean?
And how can you fix your code?
What does that error message mean?
The last line is in a Python traceback message is the most important one.
TypeError: can only concatenate str (not "int") to str
That last line says the exception type (TypeError
) and the error message (can only concatenate str (not "int") to str
).
This error message says something similar:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Both of these error messages are trying to tell us that we’re trying to use the +
operator (used for string concatenation in Python) between a string and a number.
You can use +
between a string and a string (to concatenate them) or a number and a number (to add them).
But in Python, you cannot use +
between a string and a number because Python doesn’t do automatic type coercion.
Type conversions are usually done manually in Python.
How do we fix this?
How we fix this will depend on our needs.
Look at the code the error occurred on (remember that tracebacks are read from the bottom-up in Python).
File "copyright.py", line 4, in <module>
statement = "Copyright " + year
Ask yourself “what am I trying to do here?”
You’re likely either trying to:
- Build a bigger string (via concatenation)
- Add two numbers together
- Use
+
in another way (e.g. to concatenate lists)
Once you’ve figured out what you’re trying to do, then you’ll then need to figure out how to fix your code to accomplish your goal.
Converting numbers to strings to concatenate them
If the problematic code is meant to concatenate two strings, we’ll need to explicitly convert our non-string object to a string.
For numbers and many other objects, that’s as simple as using the built-in str
function.
We could replace this:
statement = "Copyright " + year
With this:
statement = "Copyright " + str(year)
Though in many cases it may be more readable to use string interpolation (via f-strings):
statement = f"Copyright {year}"
This works because Python automatically calls the str
function on all objects within the replacement fields in an f-string.
Converting other objects to strings
Using the str
function (or an f-string) will work for converting a number to a string, but it won’t always produce nice output for other objects.
For example when trying to concatenate a string and a list:
>>> names = ["Judith", "Andrea", "Verena"]
>>> user_message = "Users include: " + names
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "list") to str
You might think to use str
to convert the list to a string:
>>> user_message = "Users include: " + str(names)
This does work, but the resulting string might not look quite the way you’d expect:
>>> print(user_message)
Users include: ['Judith', 'Andrea', 'Verena']
When converting a list to a string you’ll likely want to join together the list items using the string join
method.
>>> user_message = "Users include: " + ", ".join(names)
>>> print(user_message)
Users include: Judith, Andrea, Verena
Other types of objects may require a different approach: the string conversion technique you use will depend on the object you’re working with and how you’d like it to look within your string.
Converting strings to numbers to add them
What if our code isn’t supposed to concatenate strings?
What if it’s meant to add numbers together?
If we’re seeing one of these two error messages while trying to add numbers together:
TypeError: can only concatenate (not "int") to str
TypeError: unsupported operand type(s) for +: 'int' and 'str'
That means one of our “numbers” is currently a string!
This often happens when accepting a command-line argument that should represent a number:
$ python saving.py 100
Traceback (most recent call last):
File "saving.py", line 7, in <module>
total += sys.argv[1]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Command-line arguments are often an issue because all command-line arguments come into Python as strings.
So the sys.argv
list in that saving.py
program might look like this:
>>> sys.argv
['saving.py', '100']
Note: If command-line arguments are the issue, you may want to look into using argparse
to parse your command-line arguments into the correct types.
This numbers-represented-as-strings issue can also occur when prompting the user with the built-in input
function.
>>> total = 0
>>> user_input = input("Also add: ")
Also add: 100
>>> total += user_input
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
The input
function stores everything the user entered into a string:
Regardless of how it happened, if you want to convert your string which represents a number to an actual number, you can use either the built-in float
function or the built-in int
function:
>>> user_input
'100'
>>> deposit = float(user_input)
>>> deposit
100.0
>>> deposit = int(user_input)
>>> deposit
100
The float
function will accept numbers with a decimal point.
The int
function will only accept integers (numbers without a decimal point).
Remember: type conversions usually need to be explicit
That can only concatenate str (not "int") to str
error message shows up frequently in Python because Python does not have type coercion.
Whenever you have a string and a non-string and you’d like to either sum them with +
or concatenate them with +
, you’ll need to explicitly convert your object to a different type.
All data that comes from outside of your Python process starts as binary data (bytes) and Python typically converts that data to strings.
Whether you’re reading command-line arguments, reading from a file, or prompting a user for input, you’ll likely end up with strings.
If your data represents something deeper than a string, you’ll need to convert those strings to numbers (or whatever type you need):
>>> c = a + int(b)
>>> a, b, c
(3, '4', 7)
Likewise, if you have non-strings (whether numbers, lists, or pretty much any other object) and you’d like to concatenate those objects with strings, you’ll need to convert those non-strings to strings:
>>> year = 3000
>>> message = "Welcome to the year " + str(year) + "!"
>>> print(message)
Welcome to the year 3000!
Though remember that f-strings might be a better option than concatenation:
>>> year = 3000
>>> message = f"Welcome to the year {year}!"
>>> print(message)
Welcome to the year 3000!
And remember that friendly string conversions sometimes require a bit more than a str
call (e.g. converting lists to strings).
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
TypeError: can only concatenate str (not “int”) to str” occurs if you try to concatenate a string with an integer (int
object).
Here’s what the error looks like on Python 3.
Traceback (most recent call last):
File "/dwd/sandbox/test.py", line 6, in
output = 'User: ' + user['name'] + ', Score: ' + user['score']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~
TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode
Exit fullscreen mode
Python 2.7 displays a slightly different error:
Traceback (most recent call last):
File "test.py", line 6, in
output = 'User: ' + user['name'] + ', Score: ' + user['score']
TypeError: cannot concatenate 'str' and 'int' objects
Enter fullscreen mode
Exit fullscreen mode
But it occurs for the same reason: concatenating a string with an integer.
How to fix “TypeError: can only concatenate str (not “int”) to str”
If you need to use the +
operator, check if the operands on either side are compatible. Remember: birds of a feather flock together 🦜 + 🦜
Python – as a strongly-typed programming language – doesn’t allow some operations on specific data types. For instance, it disallows adding 4
with '4'
because one is an integer (4
) and the other is a string containing a numeric character ('4'
).
This TypeError might happen in two scenarios:
- Scenario #1: when concatenating a string with a numeric value
- Scenario #2: when adding two or more numbers
Let’s explore the solutions.
⚠️ Scenario #1: when concatenating a string with a numeric value
Python syntax disallows the use of a string and a number with the addition (+
) operator:
# ⛔ Raises TypeError: can only concatenate str (not “int”) to str
user = {
'name': 'John',
'score': 75
}
output = 'User: ' + user['name'] + ', Score: ' + user['score']
print(output)
Enter fullscreen mode
Exit fullscreen mode
In the above example, user['score']
contains a numeric value (75
) and can’t be directly concatenated to the string.
Python provides various methods for inserting integer values into strings:
- The
str()
function - Formatted string literals (a.k.a f-strings)
- Printf-style formatting
- Using
print()
with multiple arguments (ideal for debugging)
The str()
function: This is the easiest (and probably the laziest) method of concatenating strings with integers. All you need to do is to convert the numbers into string values with the str()
function:
user = {
'name': 'John',
'score': 75
}
print('User: ' + user['name'] +', Score: ' + str(user['score']))
# output: User: John, Score: 75
Enter fullscreen mode
Exit fullscreen mode
Although it’s easy to use, it might make your code harder to read if you have multiple numbers to convert.
Formatted string literals (a.k.a f-strings): f-strings provide a robust way of inserting integer values into string literals. You create an f-string by prefixing it with f
or F
and writing expressions inside curly braces ({}
):
user = {
'name': 'John',
'score': 75
}
print(f'User: {user["name"]}, Score: {user["score"]}')
# output: User: John, Score: 75
Enter fullscreen mode
Exit fullscreen mode
Please note that f-string was added to Python from version 3.6. For older versions, check out the str.format()
function.
Printf-style formatting: In the old string formatting (a.k.a printf-style string formatting), we use the %
(modulo) operator to generate dynamic strings (string
%
values
).
The string operand is a string literal containing one or more placeholders identified with %
, while the values operand can be a single value or a tuple of values.
user = {
'name': 'John',
'score': 75
}
print('User: %s, Score: %s' % (user['name'], user['score']))
# output: User: John, Score: 75
Enter fullscreen mode
Exit fullscreen mode
When using the old-style formatting, check if your format string is valid. Otherwise, you’ll get another TypeError: not all arguments converted during string formatting.
Using print()
with multiple arguments (ideal for debugging): If you only want to debug your code, you can pass the strings and the integers as separate arguments to the print()
function.
All the positional arguments passed to the print()
function are automatically converted to strings – like how str()
works.
user = {
'name': 'John',
'score': 75
}
print('User:', user)
# output: User: {'name': 'John', 'score': 75}
Enter fullscreen mode
Exit fullscreen mode
As you can see, the print()
function outputs the arguments separated by a space. You can change the separator via the sep
keyword argument.
⚠️ Scenario #2: when adding two or more numbers
This error doesn’t only happen when you intend to concatenate strings. It can also occur when you try to add two or more numbers, but it turned out one of them was a string. For instance, you get a value from a third-party API or even the input()
function:
devices = input('How many iphones do you want to order: ')
unit_price = 900
# total cost with shipping (25)
total_cost = devices * unit_price + 25
Enter fullscreen mode
Exit fullscreen mode
The above code is a super-simplified program that takes iPhone pre-orders. It prompts the user to input the number of devices they need and outputs the total cost – including shipping.
But if you run the code, it raises TypeError: can only concatenate str (not “int”) to str.
The reason is the input()
reads an input line and converts it to a string. And once we try to add the input value (which is now a string) to 25
, we get a TypeError.
The reason is Python’s interpreter assumes we’re trying to concatenate strings.
To fix the issue, you need to ensure all operands are numbers. And for those that aren’t, you can cast them to an integer with the int()
function:
devices = input('Number of iphones: ')
unit_price = 900
# total cost with shipping (25)
total_cost = int(devices) * unit_price + 25
Enter fullscreen mode
Exit fullscreen mode
It should solve the problem.
Alright, I think that does it! I hope this quick guide helped you fix your problem.
Thanks for reading!
❤️ You might like:
- TypeError: can only concatenate str (not “bool”) to str (Fixed)
- TypeError: can only concatenate str (not “dict”) to str (Fixed)
- TypeError: can only concatenate str (not “list”) to str (Fixed)
- Not all arguments converted during string formatting error in Python (Fixed)