2009-12-11 286 views
65

假設我有一個字符串,它是另一個字符串的反斜線轉義版本。有沒有簡單的方法,在Python中,以避免字符串?我可以,例如,做:如何在python中不轉義反斜線轉義的字符串?

>>> escaped_str = '"Hello,\\nworld!"' 
>>> raw_str = eval(escaped_str) 
>>> print raw_str 
Hello, 
world! 
>>> 

然而,涉及通過一個(可能不被信任)字符串的eval(),這是一個安全隱患。在標準庫中是否有一個函數接受一個字符串併產生一個沒有安全影響的字符串?

回答

111
>>> print '"Hello,\\nworld!"'.decode('string_escape') 
"Hello, 
world!" 
+5

+1 Oy公司我喜歡所有的很酷的技巧,我從SO學習! – jathanism 2009-12-11 01:08:34

+0

好戲,但並沒有完全爲我工作 – sleepycal 2014-11-21 22:04:43

+2

有沒有什麼是與Python 3兼容? – thejinx0r 2015-04-04 01:37:48

18

您可以使用ast.literal_eval這是安全的:

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. (END)

像這樣:

>>> import ast 
>>> escaped_str = '"Hello,\\nworld!"' 
>>> print ast.literal_eval(escaped_str) 
Hello, 
world! 
+0

xy問題再一次咬我。感謝這! – trianta2 2015-11-04 22:01:51

+1

在字符串中有一個轉義的分號會打破此代碼。引發語法錯誤「行後續字符出現意外字符」 – darksky 2016-07-01 23:00:27

+1

@darksky注意到'ast'庫需要引號(無論是''''''',甚至是'「」「或''''')在您的escaped_str周圍,因爲它實際上是試圖將其作爲Python代碼運行,但增強了安全性(防止字符串注入) – no1xsyzy 2017-12-04 14:01:16