我可以用Python中的5位unicode替换字符串吗?un

时间:2013-02-05 13:29:16

标签: python unicode

早些时候,我问过这个问题: How to convert some character into five digit unicode one in Python 3.3?

但今天我在打印时发现Capital U代码点有效,但是当我在文件中尝试它时,结果却失败了。为什么呢?

import re

f = codecs.open('test.txt', 'r', encoding="utf-8")
g = codecs.open('test_output.txt', 'w', encoding="utf-8")
fin = f.read()
output = re.sub('m', '\U000243D0', fin)
g.write(output)

1 个答案:

答案 0 :(得分:1)

这对我来说很好用:

import re

with open('/tmp/test.txt', 'w', encoding='utf8') as testfile:
    testfile.write("I don't go to school on mondays")

with open('/tmp/test.txt', 'r', encoding='utf8') as testfile, open('/tmp/test_output.txt', 'w', encoding='utf8') as testout:
    output = re.sub('m', '\U000243D0', testfile.read())
    testout.write(output)

with open('/tmp/test_output.txt', 'r', encoding='utf8') as testfile:
    print(repr(testfile.read()))

输出

"I don't go to school on ondays"