简体   繁体   中英

How do I convert a string into a string of bytes in python 2.7

I'm trying to convert a string coming from raw_input() into a "string of bytes". When I type the variable manually (in the code) it works fine, as it returns me a length of 5. However, when I try to enter the "string of bytes" with raw_input() it returns me a length of 20.

>>> x='\xB2\xB2\xB3\xB4\x01'
>>> len(x)
5
>>> x=raw_input()
\xB2\xB2\xB3\xB4\x01
>>> len(x)
20

I would like to know why this is happening and how can I fix it. Thanks in advance.

When you submit the string "\\xB2\\xB2\\xB3\\xB4\\x01" to raw_input() it automatically escapes the \\ characters because it thinks you mean to enter them as part of a string. This results in the representation of the string to read like this:

In [2]: x=raw_input()
\xB2\xB2\xB3\xB4\x01

In [3]: x
Out[3]: '\\xB2\\xB2\\xB3\\xB4\\x01'

In [4]: print x
\xB2\xB2\xB3\xB4\x01

Unfortunately the answer to your question is basically that you shouldn't be manually entering a string of bytes to raw_input() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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