Aasam Tasaddaq
Aasam Tasaddaq

Reputation: 665

Python Escape Sequence and String Manipulation

I have the following two vars:

a = chr(92) + 'x11'
b = '\x11'
print 'a is: ' + a
print 'b is: ' + b

The result of these print statemtents:

a is: \x11
b is: <|        # Here I am just showing a representation of the symbol that is printed for b

How can I make it so that variable a prints the same thing as var b using the chr(92) call? Thank you in advance.

Upvotes: 2

Views: 4686

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208615

Check out the documentation for string literals.

Backslash is an escape character in Python strings, so to include a literal backslash in your string you need to escape them by using two consecutive backslashes. Alternatively, you can suppress the escaping behavior of backslashes by using a raw string literal, which is done by prefixing the string with r. For example:

  • Escaping the backslash:

    b = '\\x11'
    
  • Using a raw string literal:

    b = r'\x11'
    

If I am misinterpreting your question and b should be '\x11' or equivalently chr(17), but you just want it to display in the escaped format, you can use repr() for that:

>>> b = '\x11'
>>> print 'b is: ' + repr(b)
b is: '\x11'

If you don't want the quotes, use the string_escape encoding:

>>> print 'b is: ' + b.encode('string_escape')
b is: \x11

Or to get a to be the same as b, you can use a.decode('string_escape').

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251538

The other answers are showing you how to make b give you what you get in a. If you want a to give you what you get in b (which is what you're asking, if I read you correctly), you need to decode the escape sequence:

>>> a
u'\\x11'
>>> a.decode('string-escape')
'\x11'

You can also use unicode-escape instead of string-escape if you want a unicode string as the result.

Upvotes: 3

Hunter McMillen
Hunter McMillen

Reputation: 61540

\x11 appears to be the hex value for a ^Q control character in ASCII:

\021  17  DC1  \x11  ^Q    (Device control 1) (XON) (Default UNIX    START char.)

You need to escape the \ to get the literal \x11

Upvotes: 0

Related Questions