2017-04-02 60 views
1

有些新的蟒蛇,说实话不是很熟悉的编码在PythonPython的 - 如何逃脱序列转换为字符串文字

设在解析text/html的投入,我结束了看起来像下面的路径

line = \\dfslocation\prj\gct\asw\sw_archive 

然而,在处理的早期,它似乎像逃脱序列“\ a”和\“T”已经为文字不再存储。

literal_line = "%r"%(line) 
print literal_line 

\\dfslocation\prj\gct\x07sw\\sw_archive 

我最好的猜测是它发生了,当我试图邮件转换为文本

for part in self.msg.walk(): 
    if part.get_content_type().startswith('text/plain'): 
    plain_text_part = part.get_payload(decode=False) 
    received_text += '\n' 
    received_text += plain_text_part 

received_text = received_text.encode('ascii', 'ignore') 

后来我想用这个作为一个网络路径,这将需要这是它的字面形式 - 即\ a,而不是\ x07(ASCII贝尔字符)

我能想到的蛮力方法,将搜索所有转义序列https://docs.python.org/2.0/ref/strings.html,并用相应的字符串文字替换它们。

有没有更好的方法来做到这一点?

谢谢

回答

0

尝试将行变量内容存储为raw而不是ASCII。

如果存储,因为它是在\a将转换为:x07

>>> line = "\\dfslocation\prj\gct\asw\sw_archive" 
>>> line 
'\\dfslocation\\prj\\gct\x07sw\\sw_archive' 

但是,如果你保存为原料,采用r'<your_ascii_text>'格式,它不会转换为特殊字符。

>>> line = r'\\dfslocation\prj\gct\asw\sw_archive' 
>>> print line 
\\dfslocation\prj\gct\asw\sw_archive 
>>> 

原始字符串处理\a\a,使它们非常适用于窗口的文件名和正则表达式。

相关问题