值错误:此cas中的\x转义无效

2024-10-01 13:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Why is ‘\x’ invalid in Python?

realId = 'Test'
id = ""
for x in realId:
 id += '\x'+str(ord(x))
print id

老实说,我对python和askii转换还很陌生,所以这应该是一个快速的答案。我在创建这个字符串时遇到了一个错误,有人愿意给我指出正确的方向吗?在


Tags: intestidforis老实printstr
3条回答

您所要做的是不可能的,因为\x__是字符串语法的一部分,不能动态执行。但是,您可以使用chr来获得等效字符:

>>> chr(0x01)
'\x01'
>>> chr(0x41)
'A'

你在找这个吗?在

realId = 'Test'
id = ""
for x in realId:
   id += r'\x%02x' % ord(x)
print id  # \x54\x65\x73\x74

这就是你要找的吗?在

>>> realId = 'Test'
>>> id = ""
>>> for x in realId:
...     id += r'\x'+str(ord(x))
... 
>>> print id
\x84\x101\x115\x116

相关问题 更多 >