Python。将转义的 utf 字符串转换为 utf 字符串

标签 python

有没有内置的方法可以做到这一点?

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/

相关文章:

python - 谷歌colab中spacy的位移

python - 在Python中加载包含Python API代码的共享库?

python - pip 安装失败,出现 : OSError: [Errno 13] Permission denied on directory

python - 在实例方法中更改类实例

python - 在字符串中添加一个空格

python - 如何消除数据框中的嵌套循环

python - WxPython - 使用按钮打开一个新窗口

python - 使用 sympy.diffgeom.CoordSystem 连接两个坐标系

python - 如何查看 sqlite3 Python 模块在 Ubuntu 16.04 上使用的 sqlite3 二进制文件?

python - Debug = True 时 Django 错误报告电子邮件