python 3: how to make strip() work for bytes

There are two issues here, one of which is the actual issue, the other is confusing you, but not an actual issue. Firstly:

Your string is a bytes object, ie a string of 8-bit bytes. Python 3 handles this differently from text, which is Unicode. Where do you get the string from? Since you want to treat it as text, you should probably convert it to a str-object, which is used to handle text. This is typically done with the .decode() function, ie:

somestring.decode('UTF-8')

Although calling str() also works:

str(somestring, 'UTF8')

(Note that your decoding might be something else than UTF8)

However, this is not your actual question. Your actual question is how to strip a bytes string. And the asnwer is that you do that the same way as you string a text-string:

somestring.strip()

There is no strip() builtin in either Python 2 or Python 3. There is a strip-function in the string module in Python 2:

from string import strip

But it hasn't been good practice to use that since strings got a strip() method, which is like ten years or so now. So in Python 3 it is gone.


>>> b'foo '.strip()
b'foo'

Works just fine.

If what you're dealing with is text, though, you probably should just have an actual str object, not a bytes object.


I believe you can use the "str" function to cast it to a string

print str(somestring).strip()

or maybe

print str(somestring, "utf-8").strip()

Tags:

Python 3.X