简体   繁体   中英

python 2.7 add '\' to a string

  a = hex(1)
  b = a[1] + a[0] + a[2]

I am trying to turn my hex to the hex with \\ bracket in it since those work with sockets.

a = hex(1) is 0x1 in hex and \\x01 is what I need. So what I did is

b = a[1] + a[0] + a[2] 

which turns it into x01 as I would want. However I cant added the '\\' in python

b = '\' + a[1] + a[0] + a[2]

gives me an error

I assume you don't want a literal backslash followed by x01 , but the character \\x01 :

>>> a = hex(1)
>>> b = chr(int(a[2:], 16))
>>> b
'\x01'

int parses the string "1" as a base-16 number, and chr converts the resulting number into a character with that codepoint.

Note that the result does not contain any backslashes, and is instead a length-one string, with \\x01 being merely a representation of the "Start of Heading" control character, also known as Ctrl+A .

>>> len('\x01')
1
b = '\\' + a[1] + a[0] + a[2]
print(b)

'\\' is a special character in python, the "escape character". For example '\\n' represents a newline and '\\t' a tab. You can also "escape" the escape character by using a double backslash. So '\\\\' will print a single backslash.

>>> print("\{number}".format(number=hex(1)))
\0x1

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