Python 中正确的八进制转义 UTF-8 字符方法

3
我需要在Python中获取UTF-8字符的八进制转义序列,想知道有没有更简单的方法来实现我想要的功能,例如是否有我忽视的标准库中的内容。我有一个临时的字符串操作函数,但希望有更好的解决方案。
我想从(例如)中获取: 到: \360\220\205\245 目前我正在这样做:
char = '\U00010165' # this is how Python hands it over to me
char = str(char.encode())    
# char = "b'\xf0\x90\x85\xa5'"

arr = char[4:-1].split(“\\x”)
# arr = ['f0', '90', '85', 'a5']

char = ''
for i in arr:
    char += '\\' + str(oct(int(i,16)))

# char = \0o360\0o220\0o205\0o245
char = char.replace("0o", "")

有什么建议吗?

2
下次请尽量粘贴实际的代码,这样就不用费力地将所有花哨的引号替换为Python能够识别的ASCII引号了。 - Martijn Pieters
1个回答

4
使用format(i, '03o')格式化八进制数字时,不会出现前导的0o标识符。或者可以使用str.format()来包含文本中的反斜杠:
>>> format(16, '03o')
'020'
>>> '\\{:03o}'.format(16)
'\\020'

只需循环遍历编码后的 bytes 值即可;每个字符都被作为整数产生:

char = ''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')])

演示:

>>> char = '\U00010165'
>>> ''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')])
'\\360\\220\\205\\245'
>>> print(''.join(['\\{:03o}'.format(c) for c in char.encode('utf8')]))
\360\220\205\245

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接