Skip to content Skip to sidebar Skip to footer

Typeerror: A Bytes-like Object Is Required, Not 'str' But Type Is 'bytes'

So I'm trying to replace some chars in string but python doesn't recognize its type correctly. Any ideas why is that?? ... print(type(word)) word.replace('0', 'O') ...

Solution 1:

The replace() method, when used on a bytes object, requires bytes objects as arguments too.

So instead of:

word.replace('0', 'O')

write:

word.replace(b'0', b'O')

However, if you're text processing, I wonder why you work with bytes objects instead of str objects. Working directly on strings makes more sense then. So, make sure that word is of type str instead of bytes and then word.replace('0', 'O') would work as expected. To do this, your code only needs two modifications:

  • remove the following statement: line = line.encode("ascii")
  • in get_type_of_word() just use c instead of chr(c)

Also note that word.replace('0', 'O') has no effect, since it does not really change the word but returns a (modified) copy of it. So you should assign it to have any effect, e.g. word = word.replace('0', 'O').

Post a Comment for "Typeerror: A Bytes-like Object Is Required, Not 'str' But Type Is 'bytes'"