정규표현식 사용할 때 escape에러 질문입니다.
조회수 1096회
'A lesson for all of us: "If we do not offer the body and mind a period of rest, retreat, and recovery, our \x93engagement\x94 with the world becomes a form of self-injury, of overload. We don\x92t develop resistance or resilience. '
이런 문장에서 "\x" 이 부분을 없애고 싶어서 정규식 이용해서
sentence = re.sub("\\\x", "", sentence)
이렇게 코드를 짰는데
incomplete escape \x at position 0
이런 에러가 뜨네요..
어떻게 해야하나요?
1 답변
-
정규표현식을 사용하실 때는 아래 regex변수와 같이
r'정규표현식'
형태로 쓰시는게 좋아요. raw string이라고 합니다.import re sentence = 'A lesson for all of us: "If we do not offer the body and mind a period of rest, retreat, and recovery, our \x93engagement\x94 with the world becomes a form of self-injury, of overload. We don\x92t develop resistance or resilience. ' regex = r'\\x' sentence = re.sub(regex, "", sentence) print(sentence)
r을 붙이면 백슬래시를 문자열에서 별도 처리를 안하고 그대로 인식합니다. 다음 코드를 실행해 보세요.
message1 = 'Hello\nWorld' print(message1) print("======") message2 = r'Hello\nWorld' print(message2)
댓글 입력