geo*_*gij 12 python escaping python-3.x
是否可以使用其十六进制值可视化python字符串中的不可打印字符?
例如,如果我有一个带换行符的字符串,我想替换它\x0a
.
我知道有repr()
哪些会给我...... \n
,但我正在寻找十六进制版本.
eca*_*mur 14
我不知道任何内置方法,但使用理解相当容易:
import string
printable = string.ascii_letters + string.digits + string.punctuation + ' '
def hex_escape(s):
return ''.join(c if c in printable else r'\x{0:02x}'.format(ord(c)) for c in s)
Run Code Online (Sandbox Code Playgroud)
Car*_*ate 10
我有点迟到了,但如果你需要它进行简单的调试,我发现这有效:
string = "\n\t\nHELLO\n\t\n\a\17"
procd = [c for c in string]
print(procd)
# Prints ['\n,', '\t,', '\n,', 'H,', 'E,', 'L,', 'L,', 'O,', '\n,', '\t,', '\n,', '\x07,', '\x0f,']
Run Code Online (Sandbox Code Playgroud)
丑陋,但它帮助我在字符串中找到不可打印的字符.
您必须手动进行翻译;例如,使用正则表达式遍历字符串,并用等效的十六进制替换每次出现。
import re
replchars = re.compile(r'[\n\r]')
def replchars_to_hex(match):
return r'\x{0:02x}'.format(ord(match.group()))
replchars.sub(replchars_to_hex, inputtext)
Run Code Online (Sandbox Code Playgroud)
上面的示例仅匹配换行符和回车符,但是您可以扩展匹配的字符,包括使用\x
转义码和范围。
>>> inputtext = 'Some example containing a newline.\nRight there.\n'
>>> replchars.sub(replchars_to_hex, inputtext)
'Some example containing a newline.\\x0aRight there.\\x0a'
>>> print(replchars.sub(replchars_to_hex, inputtext))
Some example containing a newline.\x0aRight there.\x0a
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24838 次 |
最近记录: |