Online Tutorials & Training Materials | STechies.com
Register Login

TypeError expected string or bytes-like object

14 Jun 2020 8:53 am || 1000

You might have used various functions in Python. While working with functions, there may be an error called “TypeError expected string or bytes-like object”. This is usually encountered when a function that you are using or have defined is fed an integer or float. It might be expecting a string or byte like object but as it has received something else, it raises an error.

The way to fix this error is to pass the correct argument to the function. You can change the syntax or convert the parameters into the required types.

We will take a closer look at the different scenarios where the error is raised. Subsequently, we will try to find their solutions.

Examples of TypeError expected string or bytes-like object

Example:

import re 

# Declared Variable as Integer
strtoreplace = 1121

textonly = re.sub("[^a-zA-Z]", " ",strtoreplace)
print('Print Value: ', textonly)

Output:

Traceback (most recent call last):
  File "pyprogram.py", line 6, in <module>
    textonly = re.sub("[^a-zA-Z]", " ",strtoreplace)
  File "C:\Python38\lib\re.py", line 208, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

TypeError expected string or bytes-like object

Solution Example:

import re 

# Declared Variable as Integer
strtoreplace = 1121

textonly = re.sub("[^a-zA-Z]", " ",str(strtoreplace))
print('Print Value: ', textonly) 

This error is encountered as there a couple of values in the code that are floats. In order to run the code successfully, you have to convert some value into strings. Before passing the values into the re.sub() function, you can convert into a string using the str() function.


Comments


View previous comments