'TypeError: a bytes-like object is required, not 'str' caused by split function

I have been moving some of my scripts from python 2.7 to python3 (3.6.8). While fixing one of my scripts, i am getting the error mentioned in subject line.

the part of the script where i am getting error at is as below.

info = conn.execute_command("Info")
lines = info.split('\n')

When i run this script i get an error copied below.

lines = info.split('\n')
TypeError: a bytes-like object is required, not 'str'

I am trying to get lines split at '\n' in the response for info. However i am not sure what is the syntax here, to get rid of this error. Any suggestions...!!!



Solution 1:[1]

It looks like info is a bytesstring, so what you should do is:

lines = info.split(b"\n")

But do note that lines would be a list of bytesstrings.

You could also do the following:

info = conn.execute_command("Info")
lines = info.decode("utf-8").split('\n')

then all the elements in lines will be normal strings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ewong