gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:02 26 4
gpt4 key购买 nike

我需要在 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", "")

有什么建议吗?

最佳答案

使用 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

关于python - 在 Python 中八进制转义 UTF-8 字符的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21858021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com