CopeAleph CopeAleph - 1 month ago 12
Python Question

Python 3, TypeError: a bytes-like object is required, not 'str'

async def chuck(self):
joketype = 'nerdy' if randint(0, 100) < 50 else 'explicit'
cnjoke = requests.get('http://api.predator.wtf/joke/?arguments={}'.format(joketype),allow_redirects = True).content

return '{}'.format(str(cnjoke.replace('&quot;', '"').replace('steal', 'steel')))


I am trying to use this api to get chuck norris jokes (don't ask lol) but it is returning this error:

return '```{}```'.format(str(cnjoke.replace('&quot;', '"').replace('steal', 'steel')))
TypeError: a bytes-like object is required, not 'str'


I am not sure what to do.

Answer
'```{}```'.format(str(cnjoke).replace('&quot;', '"').replace('steal', 'steel'))

or

'```{}```'.format(cnjoke.decode().replace('&quot;', '"').replace('steal', 'steel'))

and content returns bytes

type(cnjoke) #bytes

using text instead may be better in your case

_cnjoke = requests.get('http://api.predator.wtf/joke/?arguments={}'.format(joketype),allow_redirects = True).text
type(_cnjoke) #str