Expected string or bytes like object python ошибка

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

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

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

Приветствую, ситуация следующая. Имеется проект блога на 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

Как я понимаю, на вход поступает неверный тип данных, но вот где именно проблема (а точнее в Чём) понять не могу. Буду благодарен любым подсказкам, заранее благодарю.


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

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.

Понравилась статья? Поделить с друзьями:
  • Excel vba ошибка out of memory
  • Ex machina меридиан 113 ошибка при запуске
  • Esvmo sf 450 a коды ошибок
  • Esq частотный преобразователь ошибка е09
  • Esp bas ошибка jeep grand cherokee wk