반응형
foobar
를 foo123bar
로 어떻게 바꿀 수 있습니까?
작동하지 않습니다.
>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'
이것은 작동합니다 :
>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'
\ number
와 같은 것을 가질 때 일반적인 문제라고 생각합니다. 누구든지 이것을 처리하는 방법에 대한 힌트를 줄 수 있습니까?
해결 방법
정답은:
re.sub(r'(foo)', r'\g<1>123', 'foobar')
문서에서 관련 발췌 :
문자 이스케이프 및 backreferences as described above, \g will use the substring matched by the group named name, as defined by the (?P...) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the 레.
참조 페이지 https://stackoverflow.com/questions/5984633
반응형
'파이썬' 카테고리의 다른 글
파이썬 제거하지 않고 집합에서 요소를 검색하는 방법은 무엇입니까? (0) | 2020.10.03 |
---|---|
파이썬 Python에서 객체 목록 검색 (0) | 2020.10.03 |
파이썬 Pipe character in Python (0) | 2020.10.02 |
파이썬 PyPlot 창을 여러 개 가질 수 있습니까? 아니면 서브 플롯으로 제한됩니까? (0) | 2020.10.02 |
파이썬에서 목록을 검색하는 가장 빠른 방법 (0) | 2020.10.02 |
댓글