Joan Ràfols
Joan Ràfols

Reputation: 75

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.

Upvotes: 3

Views: 185

Answers (1)

wpercy
wpercy

Reputation: 10090

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().

Upvotes: 1

Related Questions