IT story

Python에서 첫 번째 문자열 교체

hot-time 2020. 8. 31. 08:25
반응형

Python에서 첫 번째 문자열 교체


샘플 문자열이 있습니다. 더 긴 문자열에서이 문자열의 첫 번째 발생을 빈 문자열로 어떻게 바꿀 수 있습니까?

regex = re.compile('text')
match = regex.match(url)
if match:
    url = url.replace(regex, '')

string replace () 함수는이 문제를 완벽하게 해결합니다.

string.replace (s, old, new [, maxreplace])

old 부분 문자열의 모든 항목이 new로 대체 된 문자열 s의 복사본을 반환합니다. 선택적 인수 maxreplace가 제공되면 첫 번째 maxreplace 발생이 대체됩니다.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

re.sub직접 사용 하면 다음을 지정할 수 있습니다 count.

regex.sub('', url, 1)

(참고 인수의 순서는 것을 replacement, original아니 정반대로 의심 될 수 있습니다.)

참고 URL : https://stackoverflow.com/questions/4628618/replace-first-occurrence-of-string-in-python

반응형