有没有内置的方法可以做到这一点?
rawstr = r"3 \u176? \u177? 0.2\u176? (2\u952?)"
#required str is 3 ° ± 0.2° (2θ).
有点像
In [1] rawstr.unescape()?
Out[1]: '3° ± 0.2° 2θ'
问题是如何将 rawstr 转换为 'utf-8'。
为了更清楚,请参阅我的答案。
如果有比我现在正在做的更好的选择,请回答。
最佳答案
是的,有!
对于 python 2:
print r'your string'.decode('string_escape')
对于python 3,你需要将它转化为字节,然后使用decode
:
print(rb'your string'.decode('unicode_escape'))
请注意,这在您的情况下不起作用,因为您的符号没有正确转义(即使您使用“正常”方式打印它们,它也不起作用)。
你的字符串应该是这样的:
rb'3\u00B0 \u00b1 0.2\u00B0 2\u03B8'
请注意,如果您需要将 string
转换为 python 中的 bytes
,可以使用 bytes
函数。
my_str = r'3\u00B0 \u00b1 0.2\u00B0 2\u03B8'
my_bytes = bytes(my_str, 'utf-8')
print my_bytes.decode('string_escape') # python 2
print(my_bytes.decode('unicode_escape')) # python 3
关于Python。将转义的 utf 字符串转换为 utf 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548362/