TypeError: a bytes-like object is required, not 'str' in Python
Dung Do Tien
Aug 20 2021
157
Hello, in Python 3.8.2, I'm using replace()
method to try to replace text in a string of bytes. Like this:
message = b"The cat catches a rat but it does not kill the prey"
new_msg = message.replace("rat","mouse")
print(new_msg)
But I get an error TypeError: a bytes-like object is required, not 'str'.
Traceback (most recent call last):
File "main.py", line 2, in <module>
new_msg = message.replace("rat","mouse")
TypeError: a bytes-like object is required, not 'str'
Seem code, it's so simple but I don't know why? or bytes data type does not support replacing the text of it.
Thanks for any suggestions.
Have 1 answer(s) found.
-
А1
Алина Долгова Aug 20 2021
Oh, I think you are mistaking a bout bytes datatype.
replpace()
method has supported replace text for the bytes data type.In order to rectify this all that we need to do is add ‘b’ before rat and mouse. Let us check whether it works or not.
message = b"The cat catches a rat but it does not kill the prey" new_msg = message.replace(b"rat",b"mouse") print(new_msg)
#Output b'The cat catches a mouse but it does not kill the prey'
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.