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

I mixed up Python 2 code with Python 3. In doing so, I changed

print 'String: ' + somestring 

in

 print(b'String: '+somestring) 

because I got the following error:

 Can't convert 'bytes' object to str implicitly 

But now I can’t implement string attributes like strip () because they are no longer considered as strings ...

 global name 'strip' is not defined 

for

 if strip(somestring)=="": 

How do I solve this problem between switching string to bytes and the ability to use string attributes? Is there a workaround? Please help me and thanks in advance.

+6
source share
3 answers

There are two problems here, one of which is an urgent problem, the other confuses you, but it is not an urgent problem. At first:

Your string is a byte object, i.e. a string of 8-bit bytes. Python 3 treats this differently than text, which is Unicode. Where did you get the line? Since you want to treat it as text, you should probably convert it to a str object that is used to process the text. This is usually done using the .decode () function, that is:

 somestring.decode('UTF-8') 

Although calling str () also works:

 str(somestring, 'UTF8') 

(Please note that your decoding may be something other than UTF8)

However, this is not your real question. Your actual question is how to remove the byte string. And asnwer is that you do it the same way you do a text string:

 somestring.strip() 

In Python 2 or Python, there is no built-in strip () function. In the line module in Python 2, there is a strip function:

 from string import strip 

But this was not good practice, since the strings got the strip () method, which now looks like ten years or so. So in Python 3 he left.

+9
source

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

 print str(somestring).strip() 

or maybe

 print str(somestring, "utf-8").strip() 
+2
source
 >>> b'foo '.strip() b'foo' 

It works well.

If you are dealing with text, you should probably have the actual str object, not the bytes object.

+1
source

Source: https://habr.com/ru/post/909966/


All Articles