gpt4 book ai didi

python - 如何替换 r'\xb 0' with r'\260'

转载 作者:行者123 更新时间:2023-12-01 05:32:30 26 4
gpt4 key购买 nike

如何在字符串中替换这些字符:r'\xb0' 为 r'\260',我已经尝试过:

test = u'\xb0C'
test = test.encode('latin1')
test = test.replace(r'\xb0', r'\260')

但是这不起作用。问题是,我必须将数据以八进制格式(例如“\260C”)写入文件,而不是以十六进制格式等。

最佳答案

你的意思是

>>> test.encode('unicode-escape').replace(r'\xb0', r'\260')
'\\260C'

>>> ''.join('\\%o' % ord(c) for c in test)
'\\260\\103'

或者最慷慨的方法(事实证明这是OP的要求)

>>> table = {i: unicode(chr(i)) if 32 <= i < 128 else u'\\%o' % i for i in range(256)}
>>> u'\xb0ABD\260'.translate(table)
u'\\260ABD\\260'

关于python - 如何替换 r'\xb 0' with r'\260',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19881815/

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