Re.sub erroring with “Expected string or bytes-like object”

1.3K    Asked by AkanshaChawla in Python , Asked on Apr 14, 2021

Question Description:

I have read multiple posts regarding the error “expected string or bytes-like object”, but I still can't figure it out. When I try to loop through my function:

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
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

Answered by Akansha Chawla

Your some of the values appeared to be floats, not strings. So, in order to get rid of this error do one thing just change those values into strings before passing them to re.sub. One simple way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyway even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ", # Replace all non-letters with spaces
                          str(location))

Note: This error 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.



Your Answer

Interviews

Parent Categories