有什么内置的方法可以做到这一点吗?
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'
注意,如果需要在python中将
string
转换为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 - python 。将转义的utf字符串转换为utf字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42548362/