Python expecting string or bytes object

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

Одна ошибка, с которой вы можете столкнуться при использовании 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() для первого преобразования списка в строковый объект.

Читайте также:  Result count php woocommerce

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

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

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

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

Источник

Python expecting string or bytes object

Last updated: Feb 3, 2023
Reading time · 4 min

banner

# TypeError: expected string or bytes-like object in Python

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

To solve the error, make sure to call the function with a string argument instead.

typeerror expected string or bytes like object

Here is an example of how the error occurs.

Copied!
import re my_int = 100 # ⛔️ TypeError: expected string or bytes-like object result = re.sub(r'4', '_', my_int) # 👈️ third arg must be str

We passed an integer as the third argument to the re.sub method, but the method expects a string argument.

The re.sub() method takes 3 arguments:

  1. A pattern to match in a string.
  2. The replacement string for the matches.
  3. The string in which to match the pattern.

# Convert the value to a string to solve the error

One way to solve the error is to use the str() class to convert the value to a string.

Copied!
import re my_int = 100 # ✅ convert to str result = re.sub(r'3', '_', str(my_int)) print(result) # 👉️ '___'

convert value to string to solve the error

We used the str() class to convert the integer to a string when calling re.sub() .

You might also be iterating over a sequence and calling the re.sub() method with each item.

If you aren’t sure whether all of the items in the sequence are strings, pass each to the str() class.

Copied!
import re my_list = [0, 10, 100] new_list = [] for item in my_list: result = re.sub(r'8', '_', str(item)) print(result) new_list.append(result) print(new_list) # 👉️ ['_', '__', '___']

pass each value to str class

We used a for loop to iterate over the list.

On each iteration, we pass the current item to the str() class before using re.sub() .

# Providing a fallback value for None values

If your sequence stores None values, provide an empty string as a fallback.

Copied!
import re my_value = None result = re.sub(r'6', '_', my_value or '') print(repr(result)) # 👉️ ''

provide fallback value for none values

The expression None or » evaluates to an empty string which helps us avoid the error.

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

Here is an example of how to solve the error when working with lists.

Copied!
import re from ast import literal_eval my_list = [5, 'a', 0, 'b', 1, 'c', 2, 6] # ✅ remove letters from list my_str = re.sub(r'[a-zA-Z]+', '', str(my_list)) print(my_str) # 👉️ [5, '', 0, '', 1, '', 2, 6] # ✅ remove empty strings from string new_str = my_str.replace("''", '') print(new_str) # 👉️ [5, , 0, , 1, , 2, 6] # ✅ remove double commas from string new_str = new_str.replace(", ,", ',') print(new_str) # 👉️ [5, 0, 1, 2, 6] # ✅ convert string representation of list to list my_list = literal_eval(new_str) print(my_list) # 👉️ [5, 0, 1, 2, 6] print(type(my_list)) # 👉️
  1. We first remove all letters from the list, converting the list to a string.
  2. Then we remove all empty strings from the string and replace double commas with a single comma.
  3. The last step is to use the literal_eval() method to convert the string to a list.

You might also get the error when using the re.findall() method.

# Encountering the error when using re.findall()

Here is an example of how the error occurs when using re.findall() .

Copied!
import re my_int = 100 # ⛔️ TypeError: expected string or bytes-like object, got 'int' result = re.findall(r'6', my_int)

To solve the error, convert the second argument in the call to findall() to a string.

Copied!
import re my_int = 100 result = re.findall(r'5', str(my_int)) print(result) # 👉️ ['1', '0', '0']

We used the str() class to convert a value to a string before calling re.findall() .

Here is another example of how the error occurs when using the re.findall() method.

Copied!
import re with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() # 👈️ this is a list # ⛔️ TypeError: expected string or bytes-like object m = re.findall(r'\w+th', lines) # 👈️ passing list instead of str

We passed a list to the re.findall method, but the method takes a string argument.

To solve the error, call the read() method on the file object to get a string of the file’s contents and pass the string to the findall method.

Copied!
import re with open('example.txt', 'r', encoding='utf-8') as f: my_str = f.read() print(type(my_str)) # 👉️ m = re.findall(r'\w+th', my_str) print(m) # 👉️ ['fourth', 'fifth']

The example assumes that you have a file named example.txt with the following contents:

Copied!
first second third fourth fifth

All we had to do is make sure we pass a string as the second argument to the re.findall method.

The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

# Solve the error when reading from a JSON file

If you got the error while trying to read a JSON file, use the json.load() method.

Copied!
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) # ✅ call json.load() with file obj print(my_data) # 👉️ print(my_data['name']) # 👉️ 'Alice' print(type(my_data)) # 👉️

The code sample above assumes that you have an example.json file in the same directory.

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method.

If the error persists, use your IDE to check the type of the method’s parameters.

One of the arguments the method takes must be of type str and you are passing a value of a different type.

# Checking what type a variable stores

If you aren’t sure what type of object a variable stores, use the built-in type() class.

Copied!
my_str = 'hello' print(type(my_str)) # 👉️ print(isinstance(my_str, str)) # 👉️ True my_dict = 'name': 'Alice', 'age': 30> print(type(my_dict)) # 👉️ print(isinstance(my_dict, dict)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed-in object is an instance or a subclass of the passed-in class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Solve Python TypeError: expected string or bytes-like object

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:

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

When you run the following code:

Python responds with an error as shown below:

TypeError: expected string or bytes-like object

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

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:

 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:

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:

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.

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Оцените статью