Ошибка typeerror expected string or bytes like object

Как исправить: ошибка типа: ожидаемая строка или байтовый объект

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться при использовании Python:

TypeError : expected string or bytes-like object

Эта ошибка обычно возникает, когда вы пытаетесь использовать функцию re.sub() для замены определенных шаблонов в объекте, но объект, с которым вы работаете, не состоит полностью из строк.

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, у нас есть следующий список значений:

#define list of values
x = [1, 'A', 2, 'B', 5, 'C', 'D', 'E']

Теперь предположим, что мы пытаемся заменить каждую небукву в списке пустой строкой:

import re

#attempt to replace each non-letter with empty string
x = re. sub('[^a-zA-Z]', '', x)

TypeError : expected string or bytes-like object

Мы получаем ошибку, потому что в списке есть определенные значения, которые не являются строками.

Как исправить ошибку

Самый простой способ исправить эту ошибку — преобразовать список в строковый объект, заключив его в оператор str() :

import re

#replace each non-letter with empty string
x = re. sub('[^a-zA-Z]', '', str (x))

#display results
print(x)

ABCDE

Обратите внимание, что мы не получили сообщение об ошибке, потому что использовали функцию str() для первого преобразования списка в строковый объект.

Результатом является исходный список, в котором каждая небуква заменена пробелом.

Примечание.Полную документацию по функции re.sub() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

I have read multiple posts regarding this error, but I still can’t figure it out. When I try to loop through my function:

def fix_Plan(location):
    letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          location)     # Column and row to search    

    words = letters_only.lower().split()     
    stops = set(stopwords.words("english"))      
    meaningful_words = [w for w in words if not w in stops]      
    return (" ".join(meaningful_words))    

col_Plan = fix_Plan(train["Plan"][0])    
num_responses = train["Plan"].size    
clean_Plan_responses = []

for i in range(0,num_responses):
    clean_Plan_responses.append(fix_Plan(train["Plan"][i]))

Here is the error:

Traceback (most recent call last):
  File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 48, in <module>
    clean_Plan_responses.append(fix_Plan(train["Plan"][i]))
  File "C:/Users/xxxxx/PycharmProjects/tronc/tronc2.py", line 22, in fix_Plan
    location)  # Column and row to search
  File "C:UsersxxxxxAppDataLocalProgramsPythonPython36libre.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object


One error you may encounter when using Python is:

TypeError: expected string or bytes-like object

This error typically occurs when you attempt to use the re.sub() function to replace certain patterns in an object but the object you’re working with is not composed entirely of strings.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following list of values:

#define list of values
x = [1, 'A', 2, 'B', 5, 'C', 'D', 'E']

Now suppose we attempt to replace each non-letter in the list with an empty string:

import re

#attempt to replace each non-letter with empty string
x = re.sub('[^a-zA-Z]', '', x)

TypeError: expected string or bytes-like object

We receive an error because there are certain values in the list that are not strings.

How to Fix the Error

The easiest way to fix this error is to convert the list to a string object by wrapping it in the str() operator:

import re

#replace each non-letter with empty string
x = re.sub('[^a-zA-Z]', '', str(x))

#display results
print(x)

ABCDE

Notice that we don’t receive an error because we used str() to first convert the list to a string object.

The result is the original list with each non-letter replaced with a blank.

Note: You can find the complete documentation for the re.sub() function here.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

In Python, different modules and open-source libraries provide various functions that are used to perform multiple operations. Sometimes, while dealing with a function, if the user inputs an integer or string value as an argument, the error “TypeError: expected string or bytes-like object” occurs.

Ths Python write-up will present the causes and solutions of “TypeError: expected string or bytes-like object”. The following points are discussed in this Python tutorial:

  • Reason 1: Passing Unexpected Argument Value to String Method
  • Solution 1: Use the str() Function to Convert it into a String
  • Solution 2: Provide an Empty String
  • Reason 2: Using Function That Returns Other Than String
  • Solution: Use Function That Returns String

Reason 1: Passing Unexpected Argument Value to String Method

When the user passes different data type values to a method that accepts only string type values.

The above snippet shows an error because the “re.sub()” method accepts only string value as an argument. But we pass “integer” as an argument value to a “re.sub()” method.

Solution 1: Use the str() Function to Convert it into a String

To resolve this “TypeError”, the “str()” function is utilized to convert the integer into strings. This is because the “re.sub()” method only accepts the string as an argument. The example code shown below will show you how to resolve the above error:

Code:

import re

value = 12

output = re.sub(r'[0-9]', 'ab', str(value))
print(output)

In the above code:

  • The “re” module is imported at the start to access the function “re.sub()” in the program.
  • The “re.sub()” accepts three parameter values; the first parameter, “[(0-9)]” takes the pattern value that needs to be replaced.
  • The second parameter, “ab” specifies the value that will replace the pattern. While the third parameter, “value” is necessary as it accepts the string that the replacement operation using “re.sub()” has to perform.
  • The “str()” function is utilized to convert the third argument value into a string that will solve our “TypeError”.

Output:

The above snippet shows that the substring value “1” and “2” has been successfully replaced by “ab”.

Solution 2: Provide an Empty String

If the input string value in which the “re.sub()” function performed a replacement operation is “None” then provide an empty string. The empty string will resolve this “TypeError” while executing the program.

Code:

import re

value = None

output = re.sub(r'[0-9]', 'ab', value or '')
print(output)

In the above code:

  • The logical “or” operator is used between the “none” variable and the “empty” string.
  • The “re.sub()” method evaluates the empty string because this method always takes the string or byte-like object as an argument.

Note: We can provide any string in place of “empty string”. The “re.sub()” returns the new string by replacing the occurrences of that provided string.

Output:

The above output shows an empty string because the “re.sub()” method expects a string as an argument rather than any other data type.

Reason 2: Using Function That Returns Other Than String

The error occurs when a user uses a function that returns a value other than strings, such as the “readlines()” function. The “readlines()” function returns “list” as an output. As we know, the “re.findall()” returns the “expected string or bytes-like object” error in Python when the string is not passed as an argument.

The above snippet shows the error “expected string or bytes-like object” because the “list” is used as an argument of the “re.findall()” method.

Solution: Use Function That Returns String

To resolve this error, use a function that returns string value rather than other data types. Because the “re.findall()” method only accepts the string value as a parameter. The “read()” function is used in place of “readlines()” to return string values.

Code:

import re

with open('sample.txt', 'r') as f:
    value = f.read()

    output = re.findall(r'w+on', value)

print(output)

In the above code, the “read()” function reads the file “sample.txt” and returns the value in a string. Then the “re.findall()” method accepts the value and finds the specified character from the given string without any error.

Output:

The above output returns the value from the file that ends with the “on” character.

Conclusion

The “expected string or bytes-like object” error arises when we pass various data type values to a method that expects string type parameter values. To resolve this error, various solutions are used in Python, such as using the “str()” function, providing the empty string, and using a function that returns a string type value. This article presented various reasons and solutions for the “expected string or bytes-like object” errors in Python.

Posted on Dec 29, 2022


Python TypeError: expected string or bytes-like object commonly occurs when you pass a non-string argument to a function that expects a string.

To solve this error, you need to make sure you are passing a string or bytes-like object as the argument of that function.

Two functions that commonly cause this error are:

  • re.sub()
  • re.findall()

Let’s see how to solve the error for both functions in this article.

Solve re.sub() causing TypeError: expected string or bytes-like object

The re.sub() function in Python is used to replace a pattern in a string with a replacement value.

Here’s the function signature:

re.sub(pattern, replacement, string)

Python expects a string as the third argument of the function.

When you run the following code:

import re

result = re.sub("world", "there", 1234)  # ❗️TypeError

Python responds with an error as shown below:

To solve this TypeError, you need to convert the third argument of the function to a string using the str() function:

result = re.sub("world", "there", str(1234))  # ✅

print(result)  # 1234

This solution also works when you pass a list as the third argument of the re.sub() function.

Suppose you want to replace all number values in a list with an X as shown below:

import re

list = [0, "A", 2, "C", 3, "Z"]

list_as_string = re.sub("[0-9]+", "X", list)  # ❗️

print(str)

The call to sub() function will cause an error because you are passing a list.

To solve this error, you need to convert the list to a string with the str() function.

From there, you can convert the string back to a list with the strip() and split() functions if you need it.

Consider the example below:

import re

list = [0, "A", 2, "C", 3, "Z"]

# 👇 Convert list to string with str()
list_as_string = re.sub("[0-9]+", "X", str(list))


# The following code converts the string back to list

# 👇 Remove quotation mark from the string
list_as_string = re.sub("'", "", list_as_string)

# 👇 use strip() and split() to create a new list
new_list = list_as_string.strip('][').split(', ')

print(new_list)
# ['X', 'A', 'X', 'C', 'X', 'Z']

And that’s how you solve the error when using the re.sub() function.

Solve re.findall() causing TypeError: expected string or bytes-like object

Python also raises this error when you call the re.findall() function with a non-string value as its second argument.

To solve this error, you need to convert the second argument of the function to a string as shown below:

import re

list = [0, "A", 2, "C", 3, "Z"]

# Convert list to string with str()
matches = re.findall("[0-9]+", str(list))

print(matches)
# ['0', '2', '3']

The re.findall() function already returns a list, so you can print the result as a list directly.

Conclusion

To conclude, the Python TypeError: expected string or bytes-like object error occurs when you try to pass an object of non-string type as an argument to a function that expects a string or bytes-like object.

To solve this error, you need to make sure that you are passing the correct type of object as an argument to the function.

Two functions that commonly cause this error are the re.sub() and re.findall() functions from the re module.

In some cases, you may need to convert the object to a string using the str() function when passing it as an argument.

Понравилась статья? Поделить с друзьями:
  • Ошибка typeerror dict object is not callable
  • Ошибка type pressure check tyres
  • Ошибка type mismatch в excel это
  • Ошибка twain сканера windows 10
  • Ошибка tpms hyundai solaris 2017 второе поколение