[SOLVED] Type Error: ‘can’t concat bytes to str’ in Python

Can't Concate Bytes To Str

Struggling with a ‘can’t concat bytes to str’ error in your Python code? Type errors can be frustrating, but with a little bit of understanding, they can be easily solved. In this article we try to find out what might be the possible causes of a type error and analyze one such cause “can’t concat bytes to str” in depth.

We will also look at how to solve this error and what not to do in the future to avoid running into this exception. We will also put into words what “bytes” and “str” are and how you can convert a variable from one data type to another. Let’s get into it!

Understanding Bytes and Strings in Python

In computer science, bytes are the basic unit of storing information. One byte consists of 8bits which are binary digits, that is 0 or 1. It is the smallest addressable memory unit in the architecture of a computer. Bytes can be converted into strings using the decode() or str() method.

On the other hand, python strings are just a collection of characters. They are an array of bytes that represent Unicode characters. Strings are immutable, that is, once created they cannot be altered.

Python strings can be converted into bytes of their respective Unicode characters using the bytes() method in python3.

Related: python bytes()

Understanding Type Errors in Python

A type error in python is an exception that is raised when the data type of a variable is inappropriate with respect to the operation that is being carried on it. In simpler words, when we try to operate on a particular data types with ill-suited functions, python raises a type error.

For example, when we try to subtract a string from a integer literal python will definitely raise this error.

print(1-'s')

The above code will raise a type error as follows:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(1-'s')
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Image 1
Example of a Type Error

Common Causes of Type Errors in Python

There are many causes of type error just like the one shown in the above example. Some other causes include:

  • Trying to operate on two conflicting data types.
  • Passing wrong literals to in built functions.
  • Trying to iterate over wrong or non interable variables.
  • Writing code to call non-callable objects.
  • Mistakes in index type in for or while loops.

Type Error: ‘can’t concat bytes to str

This error is raised when you try to add or concatenate a string with a byte in python. Before python was updated, the encode() function was used to convert a string into a byte. Nowadays, this method raises type errors.

The code given below will raise a error in python version>=3, but will work fine in previous versions.

f = open( 'New_files.txt', 'a+' )
text= "Hello.world"
f.write(text.encode("ascii") + "\n")

In the console we see,

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    f.write(text.encode("ascii") + "\n")
TypeError: can't concat str to bytes
Type Error Cant Concat Str To Bytes
Example of ‘can’t concat bytes to str’ Error

Fixing the ‘can’t concat bytes to str’ Error

To fix the “can’t concat bytes to str” error in Python, you can either convert bytes to strings using the decode() method or convert strings to bytes using the bytes() method. This will ensure that both literals are of the same data type, allowing them to be concatenated without raising a type error.

In order to convert a byte to a string, we can use the decode() function and to convert a string literal to bytes, we can use the bytes() method.

Let’s look at both solutions one by one.

Method 1: Converting Bytes to Strings Using decode()

We can convert bytes into strings and then concatenate them further.

The following code first converts a byte object into a string using the decode() method, let’s look at the code below:

#opening our file
f = open( 'New_files.txt', 'w' )
inin = b'Askpython.com'
# converting
outout = inin.decode() 
f.write(outout + "\n")
f.close()
f1 = open( 'New_files.txt', 'r' )
outout1 = f1.read()
print("The text in the file is= ",outout1)
f1.close()

The output will be:

The text in the file is=  Askpython.com
Type Error Fixed Method 2
Type Error (Fixed) Method 1

Method 2: Converting Strings to Bytes Using bytes()

The bytes(string_name,’utf-8′) function is used to convert a string to a byte in python 3. Let’s take a look:

#opening our file
f = open( 'New_files.txt', 'wb' )
inin = 'Askpython.com'
# converting string to byte
outout = bytes(inin, 'utf-8')
w= outout + b' is the best!'
print("now the string has become ",type(w))
f.write(w)
f.close()
f1 = open( 'New_files.txt', 'r' )
outout1 = f1.read()
print("The text in the file is= ",outout1)
f1.close()

The output will be:

now the string has become  <class 'bytes'>
The text in the file is=  Askpython.com is the best!
Type Error Fixed Method 2 1
Type Error Fixed Method (2)

Related: Integer to Binary String in Python

Conclusion

In this article we have discussed about a common error that may arise while trying to connect two different literals together. More specifically, the two literals here are bytes and strings. We have gone through the probable causes of this type error and provided solutions so that you can find the solution you were looking for without going haywire!

To know more about different errors and exceptions in python, read the official documentation.