蟒蛇。将转义的utf字符串转换为utf-string

时间:2017-03-02 06:33:37

标签: 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'。

请更清楚地查看我的回答。

请回答是否比我现在所做的更好的选择。

2 个答案:

答案 0 :(得分:2)

是的,有!

对于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

答案 1 :(得分:1)

如果你在Windows和pythonnet上安装

import clr
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as WinForms

def rtf_to_text(rtf_str):
    """Converts rtf to text"""

    rtf = r"{\rtf1\ansi\ansicpg1252" + '\n' + rtf_str + '\n' + '}'
    richTextBox = WinForms.RichTextBox()
    richTextBox.Rtf = rtf
    return richTextBox.Text

print(rtf_to_text(r'3 \u176? \u177? 0.2\u176? (2\u952?)'))
-->'3 ° ± 0.2° (2θ)'
相关问题