简体   繁体   English

如何在python 2.7中将字符串转换为字节串

[英]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". 我正在尝试将来自raw_input()的字符串转换为“字符串”。 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. 当我手动键入变量(在代码中)时,它工作正常,因为它返回长度为5.但是,当我尝试使用raw_input()输入“字符串”时,它返回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. 当您将字符串“\\ xB2 \\ xB2 \\ xB3 \\ xB4 \\ x01”提交给raw_input()它会自动转义\\字符,因为它认为您要将它们作为字符串的一部分输入。 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() . 不幸的是,你的问题的答案基本上是你不应该手动输入一个字节字符串到raw_input()

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

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