Как исправить: ошибка типа: ожидаемая строка или байтовый объект
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
Приветствую, ситуация следующая. Имеется проект блога на flask, подключил админку по средствам flask-admin. Настроил через app.py путем добавления:
admin.add_view(ModelView(Post, db.session))
admin.add_view(ModelView(Tag, db.session))
В первом случае работа с постами идет без нареканий (создать пост, редактировать, удалить). Всё отрабатывает на ура.
Но что касаться Tag то вот тут и возникает проблема. Редактируються уже созданные (в ручную) теги замечательно, но вот при создании тега, после заполнения полей вылетает следующие сообщение:
builtins.TypeError
TypeError: expected string or bytes-like object
Traceback (most recent call last):
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/model/base.py", line 1997, in create_view
model = self.create_model(form)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/contrib/sqla/view.py", line 1079, in create_model
if not self.handle_view_exception(ex):
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/contrib/sqla/view.py", line 1062, in handle_view_exception
return super(ModelView, self).handle_view_exception(exc)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/flask_admin/contrib/sqla/view.py", line 1073, in create_model
model = self.model()
File "<string>", line 4, in __init__
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 417, in _initialize_instance
manager.dispatch.init_failure(self, args, kwargs)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/home/moonz/Рабочий стол/Flask/venv/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 414, in _initialize_instance
return manager.original_init(*mixed[1:], **kwargs)
File "/home/moonz/Рабочий стол/Flask/models.py", line 50, in __init__
self.slug = slugify(self.name)
File "/home/moonz/Рабочий стол/Flask/models.py", line 8, in slugify
return re.sub(pattern, '-', s) # Заменяет их на дефис
File "/usr/lib/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
Как я понимаю, на вход поступает неверный тип данных, но вот где именно проблема (а точнее в Чём) понять не могу. Буду благодарен любым подсказкам, заранее благодарю.
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.

