1

I have a string b'helloworld\n'. I want to extract helloworld from it. For this, I am doing

print(string[1:-2])

But on output I am getting b'elloworl'.

How can I extraxt helloworld.

Thanks

Alperen
  • 3,772
  • 3
  • 27
  • 49
S Andrew
  • 5,592
  • 27
  • 115
  • 237

2 Answers2

4
print(s[0:-1])

Indexes are zero based so the h is at index zero. The ending index is non-inclusive, so go one extra.

If you want to get rid of the b you have to decode the bytes object.

print(s.decode('utf-8')[0:-1])
Antithesis
  • 161
  • 8
0

From this link, to change binary string to normal string use this:

>>> b'helloworld\n'.decode('ascii') # you can use utf8 or something else, it is up to you
'helloworld\n'

To delete whitespaces use strip():

>>> b'helloworld\n'.decode('ascii').strip()
'helloworld'
Alperen
  • 3,772
  • 3
  • 27
  • 49