Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python-3.x

I've contered a Python 2 code to Python 3. In doing so, I've changed

print 'String: ' + somestring

into

print(b'String: '+somestring)

because I was getting the following error:

Can't convert 'bytes' object to str implicitly

But then now I can't implement string attributes such as strip(), because they are no longer treated as strings...

global name 'strip' is not defined 

for

if strip(somestring)=="":    

How should I solve this dilemma between switching string to bytes and being able to use string attributes? Is there a workaround? Please help me out and thank you in advance..

like image 687
CosmicRabbitMediaInc Avatar asked Mar 05 '12 01:03

CosmicRabbitMediaInc


People also ask

What does the strip () do in Python?

What Is Strip() In Python? The Strip() method in Python is one of the built-in functions that come from the Python library. The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string.


1 Answers

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.

like image 74
Lennart Regebro Avatar answered Sep 19 '22 14:09

Lennart Regebro