정규표현식 사용할 때 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 답변

  • 좋아요

    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)
    
    • 헉!!!!!!!!!!!!!!!진짜 감사합니다ㅠㅠㅠㅠ 김한나 2018.5.30 15:47

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)