2017-04-02 61 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,使它們非常適用於窗口的文件名和正則表達式。

相關問題