简体   繁体   English

strip() 方法不适用于 str 类

[英]strip() method does not work on str class

First, I have bytes class object "myst".首先,我有bytes类对象“myst”。 I then convert it to a str class using str() , and remove the whitespace using the strip() method.然后我使用str()将其转换为str类,并使用strip()方法删除空格。 The problem is that the whitespace "\\r\\n" is not removed.问题是没有删除空格“\\r\\n”。

>>> myteststring=b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'"
>>> str(myteststring).strip()
"b'asdf\\r\\n'"

But, using the strip() method on a byte class works properly.但是,在byte类上使用strip()方法可以正常工作。

>>> byteclass=b'asdf\r\n'
>>> byteclass.strip()
b'asdf'

What's wrong here?这里有什么问题?


I think when I use str() , the resulting string includes double back slash \\\\ .我认为当我使用str() ,结果字符串包含双反斜杠\\\\ This is may be root of my problem.这可能是我问题的根源。

>>> myteststring
b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'"   # << this is problem ??

When passed a bytes object without an encoding argument, the str function would simply call the repr function to return the string representation of the given bytes object, which is why str(myteststring) returns "b'asdf\\\\r\\\\n'" , with \\r\\n escaped with additional backslashes.当传递一个没有encoding参数的bytes对象时, str函数将简单地调用repr函数来返回给定bytes对象的字符串表示,这就是str(myteststring)返回"b'asdf\\\\r\\\\n'" , \\r\\n用额外的反斜杠转义。

You can properly convert a bytes object to a string by passing to the str function an encoding argument instead:您可以通过将encoding参数传递给str函数来正确地将bytes对象转换为字符串:

>>> myteststring=b'asdf\r\n'
>>> str(myteststring, encoding='utf-8')
'asdf\r\n'
>>> str(myteststring, encoding='utf-8').strip()
'asdf'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM