簡體   English   中英

使用decode()與regex來解除此字符串的轉換

[英]Using decode() vs. regex to unescape this string

我有以下字符串,我正在試圖找出解決它的最佳做法。

解決方案必須有點靈活,因為我從API接收此輸入並且我不能完全確定當前字符結構( \\n而不是\\r )將始終相同。

'"If it ain\\'t broke, don\\'t fix it." \\nWent in for a detailed car wash.\\nThe attendants raved-up my engine when taking the car into the tunnel. NOTE: my car is...'

這個正則表達式似乎應該工作:

text_excerpt = re.sub(r'[\s"\\]', ' ', raw_text_excerpt).strip()

我已經讀過decode()可能會起作用(並且通常會是一個更好的解決方案)。

raw_text_excerpt.decode('string_unescape')

嘗試了這些方面的東西,它沒有奏效。 有什么建議? 正則表達式在這里最好嗎?

您正在尋找的編解碼器是string-escape

>>> print "\\'".decode("string-escape")
'

我不確定他們添加了什么版本,但是...可能是你正在使用的舊版本沒有它。 我在跑:

Python 2.6.6 (r266:84292, Mar 25 2011, 19:36:32) 
[GCC 4.5.2] on linux2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM