strip() 方法不适用于 str class
strip() method does not work on str class
首先,我有 bytes
class 个对象 "myst"。然后,我使用 str()
将其转换为 str
class,并使用 strip()
方法删除空格。问题是空格“\r\n”没有被删除。
>>> myteststring=b'asdf\r\n'
>>> str(myteststring)
"b'asdf\r\n'"
>>> str(myteststring).strip()
"b'asdf\r\n'"
但是,在 byte
class 上使用 strip()
方法可以正常工作。
>>> byteclass=b'asdf\r\n'
>>> byteclass.strip()
b'asdf'
这是怎么回事?
我认为当我使用 str()
时,生成的字符串包含双反斜杠 \
。这可能是我问题的根源。
>>> myteststring
b'asdf\r\n'
>>> str(myteststring)
"b'asdf\r\n'" # << this is problem ??
当传递一个没有 encoding
参数的 bytes
对象时,str
函数将简单地调用 repr
函数来 return 的字符串表示给定的 bytes
对象,这就是为什么 str(myteststring)
returns "b'asdf\r\n'"
,\r\n
用额外的反斜杠转义。
您可以通过向 str
函数传递一个 encoding
参数来正确地将 bytes
对象转换为字符串:
>>> myteststring=b'asdf\r\n'
>>> str(myteststring, encoding='utf-8')
'asdf\r\n'
>>> str(myteststring, encoding='utf-8').strip()
'asdf'
首先,我有 bytes
class 个对象 "myst"。然后,我使用 str()
将其转换为 str
class,并使用 strip()
方法删除空格。问题是空格“\r\n”没有被删除。
>>> myteststring=b'asdf\r\n'
>>> str(myteststring)
"b'asdf\r\n'"
>>> str(myteststring).strip()
"b'asdf\r\n'"
但是,在 byte
class 上使用 strip()
方法可以正常工作。
>>> byteclass=b'asdf\r\n'
>>> byteclass.strip()
b'asdf'
这是怎么回事?
我认为当我使用 str()
时,生成的字符串包含双反斜杠 \
。这可能是我问题的根源。
>>> myteststring
b'asdf\r\n'
>>> str(myteststring)
"b'asdf\r\n'" # << this is problem ??
当传递一个没有 encoding
参数的 bytes
对象时,str
函数将简单地调用 repr
函数来 return 的字符串表示给定的 bytes
对象,这就是为什么 str(myteststring)
returns "b'asdf\r\n'"
,\r\n
用额外的反斜杠转义。
您可以通过向 str
函数传递一个 encoding
参数来正确地将 bytes
对象转换为字符串:
>>> myteststring=b'asdf\r\n'
>>> str(myteststring, encoding='utf-8')
'asdf\r\n'
>>> str(myteststring, encoding='utf-8').strip()
'asdf'