2

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

4
  • 1
    try string[0:-1]. Commented Nov 9, 2017 at 6:35
  • @Ho0ony Output is b'helloworld' Commented Nov 9, 2017 at 6:36
  • b in front of string is a string literal which means string would of bytes type instead of str type and don't impact literal meaning of the string. See docs.python.org/3.3/reference/… for more info. Commented Nov 9, 2017 at 6:42
  • @apsdehal Thanks. I solved it using string.decode("utf-8") Commented Nov 9, 2017 at 6:46

2 Answers 2

5
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])
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.