2008-08-17 1 views

답변

0

당신은 분명히 모든 것을 함께 연결할 수 있습니다 :

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

는 이후 무엇인지인가요? 아니면 좀 더 간결한 것을 원하셨습니까?

-4

파이썬에는 PHP의 addslashes와 유사한 내장 escape() 함수가 있지만 내 마음에는 우스꽝스러운 unescape() 함수 (stripslashes)는 없습니다. 구조에

정규 표현식 (코드 테스트하지) : 양식 \\ (안 공백) 반환의 아무것도 필요 이론적으로

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

\ (같은 문자)

편집 :시 추가 검사, 파이썬 정규 표현식이 모두 지옥으로 깨졌습니다.

>>> 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' 

결론적으로, 무엇, 파이썬.

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 : (파이썬 소스 코드

리터럴 문자열로 적합한 캐릭터를 생성하거나 교체 연결할) Wilson's 응답있다.

cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n") 
관련 문제