2008-08-17 5 views
10

私は有効なPython [バックスラッシュ]エスケープにPHPのstriplashesを変換するために、コードの一部を書いた:PHPのにstripslashesのPythonのバージョン

cleaned = stringwithslashes 
cleaned = cleaned.replace('\\n', '\n') 
cleaned = cleaned.replace('\\r', '\n') 
cleaned = cleaned.replace('\\', '') 

どのように私はそれを凝縮することができますか?

答えて

0

あなたは明らか一緒にすべてを連結することができます

cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","") 

はあなたが後に何をしたということですか?それとももっと簡潔なものを望んでいたのですか?

-4

PythonにはPHPのaddslashesに似た組み込みのescape()関数がありますが、unescape()関数(stripslashes)はありません。私の心の中ではばかげています。救助へ

正規表現(コードテストしていない):フォーム\\(ない空白)とリターンの何かを取る理論的には

p = re.compile('\\(\\\S)') 
p.sub('\1',escapedstring) 

\(同じ文字)

編集:時さらに検査すると、Pythonの正規表現はすべて破壊されます。

>>> escapedstring 
'This is a \\n\\n\\n test' 
>>> p = re.compile(r'\\(\S)') 
>>> p.sub(r"\1",escapedstring) 
'This is a nnn test' 
>>> p.sub(r"\\1",escapedstring) 
'This is a \\1\\1\\1 test' 
>>> p.sub(r"\\\1",escapedstring) 
'This is a \\n\\n\\n test' 
>>> p.sub(r"\(\1)",escapedstring) 
'This is a \\(n)\\(n)\\(n) test' 

結論として、どのような地獄、Python。

12

全くわからないこれは..あなたが欲しいものですが、

それはあなたが合理的に効率的に正規表現を使用して処理することができ何をしたいのように聞こえる
cleaned = stringwithslashes.decode('string_escape') 
+0

私は何百万分も節約できます。 +1 –

2

import re 
def stripslashes(s): 
    r = re.sub(r"\\(n|r)", "\n", s) 
    r = re.sub(r"\\", "", r) 
    return r 
cleaned = stripslashes(stringwithslashes) 
0

使用decode('string_escape')

cleaned = stringwithslashes.decode('string_escape') 

使用

string_escape:(Pythonソースコード

で文字列リテラルとして適切な文字列を生成し、または置き換える連結)Wilson's回答など。

cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n") 
関連する問題