Python Can Only Concatenate Str Not Int to Str
Many beginner programmers have a problem with the so-called TypeError
, they wonder what they are doing wrong. Here's an example:
Exercise: Run the script and reproduce the error! Study this article to learn how to fix it!
This article will answer every question that beginners may ask about this topic.
About The TypeError
Before showing possible solutions, at first we should understand why such a mistake occurs at all, so we will repeat the basics. In Python, we have several main types of data. In this article we will focus on int
and str
.
Int represents integer numbers, for example: -523, 123, 23232.
If we want our variable to be of the int
type, we must write it down in this way:
integer = 5 print(integer) print(type(integer))
The result of this script will be as follows:
5 <class 'int'>
As we can see, our variable is 'int
' type.
Str (string) represents all kinds of texts, words, for example: 'cat'
, 'we go to sleep'
, '100 years'
.
So, how do we do it in Python?
string = 'cat' print(string) print(type(string))
Output:
cat <class 'str'>
As you can see, for our program to write the word "cat"
, we must use quotes.
After repeating the basics, you may still not notice the mistake you have made, so I will give you a possible reason for this error.
When in Python we want to do some mathematical operations, we have to use numbers (as you know for sure), so our numbers cannot be in quotation marks, namely if we want to add numbers, e.g., 10 and 5 to each other, then in Python it will look like this:
first_integer = 10 second_integer = 5 print(first_integer + second_integer)
Output:
15
A TypeError
would be caused by this script:
first_integer = '10' second_integer = 5 print(first_integer + second_integer)
Output:
Traceback (most recent call last): File "location of your python file", line 3, in <module> print(first_integer + second_integer) TypeError: can only concatenate str (not "int") to str
In this script, an error occurred with quotation marks, because first_integer
is now str
not int
, so how can we fix it?
Fix 1: Convert to the Correct Data Type Manually
Check your script and locate a potential error, then correct this line of code.
First, you look for what could have caused TypeError
. If you find something that you think might have resulted in an error, for example:
variable_name = '10'
Second, you remove the quotes and our program should work.
However, this method is ineffective for more complex programs, because you do it all manually.
Fix 2: String Conversion
Find out in which line of code TypeError
appeared and before the variables insert the data type you are interested in, when you want to add numbers to yourself, let's do so:
print(int(first_variable) + int(second_variable))
Then you are sure that these are the numbers and will definitely be added to each other, and when you want to add two words to each other, then you do so:
print(str(first_variable) + str(second_variable))
using this method, two subtitles will surely be joined together.
However, this method is not optimal when you have a lot of data that you want to combine with each other, because you have to spend a lot of time. So, lets move on to method number 3!
Fix 3: Conversion Function
Creation of a function that automatically converts a variable type into another specified type, on condition that you know that the variables do not store letters (if you want to change their type to int
). You can create a basic function that only works on 2 variables:
def change_type(f_variable, s_variable, type_): f_variable = type_(f_variable) s_variable = type_(s_variable) return f_variable, s_variable first_integer, second_integer = change_type(first_integer, second_integer, str) print('First use:') print(type(first_integer)) print(type(second_integer)) first_integer, second_integer = change_type(first_integer, second_integer, int) print('\nSecond use:') print(type(first_integer)) print(type(second_integer))
Output:
First use: <class 'str'> <class 'str'> Second use: <class 'int'> <class 'int'>
As we can see, we have managed to change our variables to the type we specified, first str
and then int
, so that we can continue writing the program.
But what if you want to do a function that will work for example on 5 variables? In that case, you need to write the function:
def change_type(list_of_variable_names, type_): for x in range(len(list_of_variable_names)): list_of_variable_names[x] = type_(list_of_variable_names[x]) first_integer = 2323 second_integer = '2333' third_integer = '4423' fourth_integer = 23231 fifth_integer = '-232' list_of_numbers = [first_integer, second_integer, third_integer, fourth_integer, fifth_integer] print('Type of values not changed:') print([type(number) for number in list_of_numbers]) print(list_of_numbers) print('\nType of values changed to str:') change_type(list_of_numbers, str) print([type(number) for number in list_of_numbers]) print(list_of_numbers) print('\nType of values changed to int:') change_type(list_of_numbers, int) print([type(number) for number in list_of_numbers]) print(list_of_numbers)
Output:
Type of values not changed: [<class 'int'>, <class 'str'>, <class 'str'>, <class 'int'>, <class 'str'>] [2323, '2333', '4423', 23231, '-232'] Type of values changed to str: [<class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>] ['2323', '2333', '4423', '23231', '-232'] Type of values changed to int: [<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>] [2323, 2333, 4423, 23231, -232]
Next, you can overwrite our variables so you can use them without a list:
first_integer, second_integer, third_integer, fourth_integer, fifth_integer = list_of_numbers
or not overwrite them and use the list for e.g. mathematical operations:
print(list_of_numbers[0] + list_of_numbers[1])
Output:
4656
Fix 4: Use an IDE like PyCharm
By using an IDE that checks for errors, such as PyCharm. If you don't know where the bug is and you're not using the IDE, it's worth downloading one to make it easier to find the bug in the code.
Alternative cause of TypeError:
If you just wanted to write something like "I have 3 cats"
and you used pluses instead of commas:
x = 'I have' y = 3 z = 'cats' print(x + y + z)
Simply change the pluses to commas:
print(x, y, z)
Summary
We repeated the basics of the int
and str
types in Python and discovered that Python will not change the variable type for us, we have to use the int()
or str()
function ourselves, depending on what we want to achieve. This article also provides 4 methods that can be used to prevent TypeError
and one other reason for this error.
I hope this blog article has helped you understand the possible cause of the problem in your script.
Sources:
- https://stackoverflow.com/questions/51252580/how-to-resolve-typeerror-can-only-concatenate-str-not-int-to-str?noredirect=1&lq=1
Where to Go From Here?
Enough theory, let's get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That's how you can become a six-figure earner easily. And that's how you polish the skills you really need in practice. After all, what's the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It's the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar "How to Build Your High-Income Skill Python" and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
Python Can Only Concatenate Str Not Int to Str
Source: https://blog.finxter.com/how-to-resolve-typeerror-can-only-concatenate-str-not-int-to-str-in-python/
0 Response to "Python Can Only Concatenate Str Not Int to Str"
Post a Comment