TypeError: encoding without a string argument in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Pioneer Gear

TypeError: encoding without a string argument in Python #

The Python "TypeError: encoding without a string argument" occurs when we use the bytes() function and specify the encoding keyword argument without providing a string value. To solve the error, pass a string to the function or convert the value using the str() class.

typeerror encoding without a string argument

Here is an example of how the error occurs.

main.py
my_text = 'hello'.encode('utf-8') print(type(my_text)) # 👉️ <class 'bytes'> my_binary_data = bytes(my_text, encoding='utf-8')

We used the bytes function and specified the encoding keyword argument but the first argument we passed to the function isn't a string.

In the example, we passed a bytes object to the function.

If you already have a bytes object, you don't have to use the bytes function.

Otherwise, make sure to pass a string for the first argument of the bytes function. You can use the str() class to convert a value to a string, e.g. str(100).
main.py
my_text = 'hello' print(type(my_text)) # 👉️ <class 'str'> my_binary_data = bytes(my_text, encoding='utf-8') print(my_binary_data) # 👉️ b'hello'

If you have a list of bytes objects that you need to convert to a list of strings, use a list comprehension.

main.py
my_list = [b'hello', b'world'] my_new_list = [str(x, 'utf-8') for x in my_list] print(my_new_list) # 👉️ ['hello', 'world']

You can use the same approach if you need to convert a list of strings to a list of bytes objects.

main.py
my_list = ['hello', 'world'] my_new_list = [bytes(x, encoding='utf-8') for x in my_list] print(my_new_list) # 👉️ [b'hello', b'world']

You can also use the decode() method if you need to decode a bytes object to a string.

main.py
my_text = 'hello'.encode('utf-8') print(type(my_text)) # 👉️ <class 'bytes'> my_str = my_text.decode('utf-8') print(type(my_str)) # 👉️ <class 'str'>

The str.encode method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_bytes = 'hello'.encode('utf-8') print(type(my_bytes)) # 👉️ <class 'bytes'> print(isinstance(my_bytes, bytes)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.