Error expected string or bytes like object

Одна ошибка, с которой вы можете столкнуться при использовании Python: TypeError : expected string or bytes-like object Эта ошибка обычно возникает, когда вы пытаетесь использовать функцию re.sub() для замены определенных шаблонов в объекте, но объект, с которым вы работаете, не состоит полностью из строк. В следующем примере показано, как исправить эту ошибку на практике. Как воспроизвести ошибку Предположим, у нас есть следующий список значений: #define list of values x = [1, 'A', 2, '

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

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

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: операнды не могли транслироваться вместе с фигурами


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

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

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:Python38libre.py", line 208, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

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.

Whenever we are working with our code to develop something and we write some code, then it may be possible our code encounters any type of error. One of those error is Typeerror, which indicates that we have not given the type of data required. For example, if we try to add 3 + “five”, then we will encounter an error named typeerror because the summation between an integer and a string is not supported in python.

Whenever this type of error occurs, we have to make sure that we are passing the same type of data that is required to complete the operation.

So, in the above sum we are required to pass an integer to add in 3.

It will eliminate our error and the operation will be successfully performed.

In this article we are going to see what causes the error named typeerror: expected string or bytes like object. Basically, we will encounter this type of error, when we are working with a regular expression and we are trying to replace any value with some other value.

Example 1:

import pandas as pd

import re

data = pd.DataFrame({‘Name’:[«Alpha», «Beta», 12, «Gamma»]})

print(data)

data[‘Name’] = [re.sub(str(i),«Omega», i) if i == 12 else i for i in                data[‘Name’]]

print(data)

Output:

PS C: Users ASUS Desktop Crazy Programmer Work > python u » c : Users ASUS Desktop Crazy Programmer Work test.py «

      Name

0  Alpha

1   Beta

2     12

3  Gamma

Traceback (most recent call last):

  File «c : Users ASUS Desktop Crazy Programmer Work test.py «,  line 8, in <module>

    data[‘Name’] = [re.sub(str(i),«Omega», i) if i == 12 else i for i in data[‘Name’]]

  File «c : Users ASUS Desktop Crazy Programmer Work test.py «, line 8, in <listcomp>

    data[‘Name’] = [re.sub(str(i),«Omega», i) if i == 12 else i for i in data[‘Name’]]

  File «C : Program Files Python382 lib re.py», line 208, in sub

    return _compile(pattern, flags).sub(repl, string, count)

TypeError: expected string or byteslike object

Here we have a DataFrame in which there are some data. In the initial stage when we are trying to print it, it is printed successfully.

Let us suppose we want to change the value of 12 in the Name column.

When we are trying to change it, it is giving the same error as we have discussed earlier.

So we have to check our code that whether the bug is there. As I described earlier this error occurs when we are trying to give any other datatype value different from its normal type which is required in the operation.

Here we are using a regular expression to replace the integer value with a string value.

So, we have to make a simple change in our code to execute it successfully.

As we can see from the documentation of regular expression that re.sub() function required its third parameter as a string but in the code we have passes it as integers.

Solution:

To resolve it, we have to pass the third parameter named I as a string. We have to write str(i) instead of I to remove this error.

import pandas as pd

import re

data = pd.DataFrame({‘Name’:[«Alpha», «Beta», 12, «Gamma»]})

print(data)

data[‘Name’] = [re.sub(str(i),«Omega», str(i)) if i == 12 else i for i in data[‘Name’]]

print(data)

Output:

PS C: Users ASUS Desktop Crazy Programmer Work > python u » c : Users ASUS Desktop Crazy Programmer Work test.py «

    Name

0  Alpha

1   Beta

2     12

3  Gamma

    Name

0  Alpha

1   Beta

2  Omega

3  Gamma

As we can see that after passing the third parameter as string, we are successfully able to perform the desired operation using regular expression.

We have successfully changed the value of integer 12 to string Omega.

Example 2:

import re

list1 = [‘Alpha’, ‘Beta’, ‘Gamma’, 40, 30]

list1 = [re.sub(str(item), «this», item) if item in range(10, 41) else item for item in list1 ]

print(list1)

Output:

PS C: Users ASUS Desktop Crazy Programmer Work > python u » c : Users ASUS Desktop Crazy Programmer Work test.py «

Traceback (most recent call last):

  File «c : Users ASUS Desktop Crazy Programmer Work test.py «, line 59, in <module>

    list1 = [re.sub(str(item), «this», item) if item in range(10, 41) else item for item in list1 ]

  File «c : Users ASUS Desktop Crazy Programmer Work test.py «, line 59, in <listcomp>

    list1 = [re.sub(str(item), «this», item) if item in range(10, 41) else item for item in list1 ]

  File «C: Program Files Python382 lib re.py «, line 208, in sub

    return _compile(pattern, flags).sub(repl, string, count)

TypeError: expected string or byteslike object

In this example, we are trying to replace some values in the list which are integers ranging from 10 to 40. We are performing this operation using sub() function in a regular expression.

As we can see that we have encountered with the same error. Whenever we are working with sub() function, then we have to cross check that we are passing the correct argument type else we will encounter the same error and it is a little bit difficult to find where the exact error is.

As we can see that we are passing the third argument as an integer that why we have encountered the error.

Solution:

We can resolve this error by passing the third argument as string type by converting it into a string.

Let’s see the corrected code and its output.

import re

list1 = [‘Alpha’, ‘Beta’, ‘Gamma’, 40, 30]

list1 = [re.sub(str(item), «this», str(item)) if item in range(10, 41) else item for item in list1 ]

print(list1)

Output:

PS C: Users ASUS Desktop Crazy Programmer Work > python u » c : Users ASUS Desktop Crazy Programmer Work test.py «

[‘Alpha’, ‘Beta’, ‘Gamma’, ‘this’, ‘this’]

As we can see that after passing the third argument as a string, we have successfully fixed the error which was shown earlier.

Conclusion

This type of error mostly occurs when we are working with sub() function in a regular expression. This work of this function is to replace a given pattern with some string. We have to be careful when we are passing its arguments. We have to check which type of argument is required to perform the operation. Whenever we pass the argument of other type which is not required then we will encounter this type of error.

Error expected string or bytes like object

Reading time В· 3 min

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

The Python «TypeError: expected string or bytes-like object» occurs when we pass an argument of a different type to a method that expects a string argument, e.g. re.sub() . To solve the error, make sure to pass a string argument to the method.

Here is an example of how the error occurs.

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

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

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

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

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

If the pattern isn’t found, the string is returned as is.

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

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

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.

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

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

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

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.

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

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.

Источник

The following error occurs when parsing web page data with beautifulSoup and processing data with regular expressions:
TypeError: Expected string or bytes-like object TypeError: Expected string or bytes-like object TypeError: Expected string or bytes-like object
It is generally caused by data type mismatch.
There are six standard data types in Python3: 

Print (type(object)) to check the current data type, where object is the object to query.

First, there is a code that looks like this:

import re
import requests
from bs4 import BeautifulSoup
import lxml

#get the html data
urlSave = "https://www.douban.com/people/yekingyan/statuses"
req = requests.get(urlSave)
soup = BeautifulSoup(req.text,'lxml')

# After parsing beautifulsoup, get the required data
times = soup.select('div.actions > span')
says = soup.select('div.status-saying > blockquote')

And then I’m going to look at it and I’m going to get the data what is the numeric type

print('says:',type(says))

The result: Says: lt; class ‘list’>
This tells us that the data selected from beautifulSoup in soup.select() is of the list type.
Next, extract the data in the list separately

#Traversing the output
for say in says:
    print(type(say))

Let’s see what type it is
The result: <<; class ‘bs4.element.Tag’> , different from the above six types
Beautiful Soup converts a complex HTML document into a complex tree structure, where each node is a Python object. All objects can be classified into four types:
TagNavigableStringBeautifulSoupComment
Use regular expressions directly to the data

for say in says:
    # Regular expressions to get the necessary data
    say = re.search('<p>(.*?)</p>',say)

There is an error
TypeError: expected string or bytes-like object
Therefore, before the regular expression, the problem is solved by converting the data type. As follows:

for say in says:
    # Convert the data type, otherwise an error will be reported
    say = str(say)
    # Regular expressions to get the necessary data
    say = re.search('<p>(.*?)</p>',say)

Read More:

  • Python PIP TypeError: expected str, bytes or os.PathLike object, not int
  • [Solved] python-sutime Error: the JSON object must be str, bytes or bytearray, not ‘java.lang.String‘
  • [Solved] TypeError: Object of type ‘bytes’ is not JSON serializable
  • [Solved] pycocotools Install Error: ERROR: Error expected str, bytes or os.PathLike object, not NoneType while executing
  • Python TypeError: coercing to Unicode: need string or buffer, NoneType found
  • [Solved] Python3.9 Pycropto RSA Error: TypeError: can’t concat str to bytes
  • [Solved] Python Error: TypeError: write() argument must be str, not bytes
  • Python TypeError: not all arguments converted during string formatting [Solved]
  • [Solved] error: when using the property decorator in Python, an error occurs: typeerror: descriptor ‘setter’ requires a ‘property’ object but
  • [How to Solve] Python TypeError: ‘int‘ object is not subscriptable
  • Python scatter chart error: TypeError: object of type ‘NoneType’ has no len()
  • [Solved] RuntimeError: unexpected EOF, expected 73963 more bytes. The file might be corrupted.
  • [Solved] TypeError: not all arguments converted during string formatting
  • Python Error: SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3:
  • TypeError: Decimal type object is not a JSON serialization solution
  • Django Issues: TypeError: “Settings” object is irreversible
  • Python Pandas Typeerror: invalid type comparison
  • [Solved] Python Error: IndentationError: expected an indented block
  • How to Solve Python AttributeError: ‘dict’ object has no attribute ‘item’
  • Tips for Python 3 string.punctuation

Various times we get stuck onto a type of error where it states that “Expected str bytes or os.pathlike object”, along with some prohibition stating that it does not expect either TextIOWrapper, does not expect list, does not expect _io.BufferedReader, etc.

We will see the situations where this error of ” Expected str, bytes or os.pathlike object” occurs and how to get rid of that problem.

It comes under the category of “TypeError” in Python. “TypeError” occurs when the data type provided in an operation or a function is inappropriate. This error can occur when an operation is carried out on an object that is either not supported for the operation or of the improper type.

How to get rid of “Expected str, bytes or os.PathLike object, not TextIOWrapper”?

This error occurs when we input a file object instead of a string when trying to open some file.

Given below is an example of how the error occurs:-

with open('file.txt', 'r', encoding='utf-8') as file1:
    lines_of_file = file1.readlines()
    print(lines_of_file)
with open(file1, 'r', encoding='utf-8') as file2:
    lines_of_file = file2.readlines()
    print(lines_of_file)

The below error occurs upon execution of the code:-

The "Expected str, bytes or os.PathLike object, not TextIOWrapper", error we get on passing the wrong data type to the input.

The command line shows the error

This error occurred because we passed the wrong data type to the open function arguments. The first argument must be a string to resolve the error. The first argument of open() must contain the name or the path of the file to be opened in the form of a string, as given below:-

with open('file.txt', 'r', encoding='utf-8') as file1:
    lines_of_file = file1.readlines()
    print(lines_of_file)
with open('new_file.txt', 'r', encoding='utf-8') as file2:
    lines_of_new_file = file2.readlines()
    print(lines_of_new_file)

We can also pass formatted strings to the argument of the function in the argument if open function without causing any error.

How to resolve “Expected str, bytes or os.PathLikeobject, not io.BufferedReader”?

This type of error occurs when we try to pass a pointer to the file, while opening the file, as shown in the below code:

file = open(file_path,'rb')
ftp.storbinary("STOR " + path_of_the_file, open(file, 'rb'))
file.close()

In the first line of the above code we have opened the file, and “file” acts as its pointer, while in the second line, while using ftp.storbinary we have used the same file pointer with the open function in the place of string or formatted string, thus, causing us the error “Expected str, bytes or os.PathLikeobject, not io.BufferedReader”.

The above type of error is resolved by passing the file_name as the open() function parameter.

The way to do this is shown in the below code:-

file = open(file_path,'rb')
ftp.storbinary("STOR " + path_of_the_file, open(file_path, 'rb'))
file.close()

What happens when we pass None to open()”?

It will cause an error: “Expected str, bytes or os.PathLikeobject, not None Type”.

This error occurs when we pass the “None” value to the open function.

A straightforward example of an instance when this type of error occurs is given below:-

file_name = None
with open(file_name, 'r', encoding='utf-8') as file1:
    lines = file1.readlines()
    print(lines)

In this, we have simply passed “None” to the open functions’ argument, and thus, it throws TypeError, namely “Expected str, bytes or os.PathLikeobject, not NoneType”.

Again, a string as the first argument will solve our problem.

How to resolve “Expected str, bytes or os.PathLikeobject, not Tuple”?

As we have seen in the previous examples, one can easily see what we have tried to do in this case.

This type of error occurs when we pass a tuple to the first argument of the open function.

Below is the given an example where we can get to see this error:-

files = 'file1.txt', 'file2.txt'
with open (files, encoding = 'utf8') as file_obj:
    file_contents = file_obj.read()
    print(file_contents)

In the above code, we have passed files as the first argument of the open(). The file is a tuple containing file1.txt and file2.txt.thus, it throws the error “Expected str, bytes or os.PathLikeobject, not Tuple”.

We should use a loop if we want to read multiple files, as in the below code. The only thing to remember is that the input to the open function should only be a string or formatted strings where we can use the expression.

files = 'file1.txt', 'file2.txt'
for filename in files:
    with open (filename, encoding = 'utf8') as file_obj:
        file_contents = file_obj.read()
        print(file_contents)

How to resolve “Expected str, bytes or os.PathLikeobject, not CSV.reader”?

This error occurs when we use the CSV.reader function inside of open function, which returns a CSV.reader object.

Given below is an example of how this error occurs:-

with open (csv.reader(filename), encoding = 'utf8') as file_obj:
        file_contents = file_obj.read()
        print(file_contents)

It can simply be resolved by using an actual string in the place of CSV.reader() in open().

with open (csv.reader(filename), encoding = 'utf8') as file_obj:
   file_contents = file_obj.read()
   print(file_contents)

Solving “Expected str, bytes or os.PathLikeobject, not Nonetype” with Anaconda installation

This error can occur while installation of anaconda on our personal computer.

We can simply delete the condarc file in the directory to solve this problem.

Solving “Expected str, bytes or os.PathLikeobject, not io.BytesIO”

This error occurs when we pass io.BytesIO object in place of a string, bytes, or pathlike object.

import io
b = io.BytesIO(b"abcd")
with open(b, 'wb') as f:
    f.write(b)

Pass the filename or file path with an open function to get what is required.

Used a generator object as a first argument of the open function?:-

The below code shows the error “Expected str, bytes or os.PathLikeobject, not generator”, as we have defined a generator function and given it as an argument to the open function.

def mygenerator():
    yield "File_name"
with open(mygenerator, 'r') as f:
   lines=f.read()
   print(lines)

Upon passing generator function, we get an error stating "expected str, bytes or os.PathLike object, not generator.

The error we get upon passing the generator object to the open() function.

These errors have only one solution: using a string or file path as an open argument, as we have seen multiple times before in this article.

FAQs

What things need to be kept in mind while dealing with open() functions in Python?

Most of the time, we get to see the TypeError stating “Expected str, bytes or os.PathLikeobject” while dealing with the open() function. This error can be avoided by passing only a string to the first argument of the open() function.

What error will it show if we pass a list instead of a string in the open() function?

It will show the TypeError as “Expected str, bytes or os.PathLikeobject, not list”.

What is os.PathLike?

It is an abstract base class for the path of files in our system.

Trending Python Articles

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

Понравилась статья? Поделить с друзьями:
  • Error expected primary expression before token перевод
  • Error expected declaration before token
  • Error expected class name before token
  • Error expected primary expression before token arduino
  • Error expected before token exit status 1 expected before token