Python

TypeError : cant concat str to bytes ( Solved )

TypeError : cant concat str to bytes  error’s root cause is performing concat operation in two incompatible objects (str and byte) . Lets understand with example, Suppose you have a text file and you want to append a new string to it. You can get the error while appending the string like cant concat str to bytes. If you are getting this error then this post is for you.

In this entire tutorial, you will learn how to solve the issue of this Typerror in a simple way.

 

TypeError : cant concat str to bytes ( Root Cause )-

The main or root cause of this error is that you are concatenating the string type to the bytes type. Mainly when you decode the strings to another format you will get the error. We need to uniform the object type before concatenation operation.

For example, I have a text file and want to append the sample text with another text. If you decode the string to another format like ASCII then you will get the error.

When you will run the below lines of code you will get this TypeError.

f = open( 'sample_text.txt', 'a+' )
text= "Here you will learn all about coding"
f.write(text.encode("ascii") + "\n")

Output

cant concat str to bytes error

 

TypeError: can’t concat str to bytes ( Solution ) –

The solution of the cant concat str to bytes is that you don’t have to decode or convert the string to bytes format. It was the case when you have a version of python less than 3.

From Python 3. xx version all strings are automatically converted to the format that is a byte.  So you will not get this typeerror.

Now if you will run the below lines of code then you will not get the error.

f = open( 'sample_text.txt', 'a+' )
text= "Here you will learn all about coding"
f.write(text + "\n")
f.close()
read_f = open( 'sample_text.txt', 'r' )
content = read_f.read()
print(content)

Output

Conclusion-

You mostly get  this typeerror when you are passing or using the wrong type of variable for the method. The above technique will solve your error if you follow the above solution.

I hope this article has helped you to clear your queries. We can typecast or encode str object to byte type object or vice versa to avoid these typeerror. If you have any doubt then you can contact us for more help.

Thanks 

Data Science Learner Team