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:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
Как исправить: ошибка типа: ожидаемая строка или байтовый объект
читать 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:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\re.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
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
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.