대소 문자를 구분하지 않음
파이썬에서 대소 문자를 구분하지 않는 문자열 대체를 수행하는 가장 쉬운 방법은 무엇입니까?
string
유형은이 기능을 지원하지 않습니다. re.IGNORECASE 옵션 과 함께 정규 표현식 하위 메소드 를 사용 하는 것이 가장 좋습니다 .
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
한 줄로 :
import re
re.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye'
re.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye'
또는 선택적 "flags"인수를 사용하십시오.
import re
re.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye'
re.sub("he\.llo", "bye", "he.llo He.LLo HE.LLO", flags=re.I) #'bye bye bye'
bFloch의 대답을 계속하면이 기능은 하나가 아니라 새로운 것으로 오래된 모든 항목을 변경합니다 (대소 문자를 구분하지 않음).
def ireplace(old, new, text):
idx = 0
while idx < len(text):
index_l = text.lower().find(old.lower(), idx)
if index_l == -1:
return text
text = text[:index_l] + new + text[index_l + len(old):]
idx = index_l + len(new)
return text
RegularExp가 필요하지 않습니다.
def ireplace(old, new, text):
"""
Replace case insensitive
Raises ValueError if string not found
"""
index_l = text.lower().index(old.lower())
return text[:index_l] + new + text[index_l + len(old):]
Blair Conrad와 같이 string.replace는 이것을 지원하지 않습니다.
정규식을 사용 re.sub
하지만 대체 문자열을 먼저 이스케이프해야합니다. 의 경우 2.6에는 flags 옵션이 re.sub
없으므로 포함 된 수정자를 사용해야합니다 '(?i)'
(또는 RE 객체, Blair Conrad의 답변 참조). 또한 또 다른 함정은 문자열이 제공되면 sub가 대체 텍스트에서 백 슬래시 이스케이프를 처리한다는 것입니다. 이것을 피하기 위해 대신 람다를 전달할 수 있습니다.
기능은 다음과 같습니다.
import re
def ireplace(old, repl, text):
return re.sub('(?i)'+re.escape(old), lambda m: repl, text)
>>> ireplace('hippo?', 'giraffe!?', 'You want a hiPPO?')
'You want a giraffe!?'
>>> ireplace(r'[binfolder]', r'C:\Temp\bin', r'[BinFolder]\test.exe')
'C:\\Temp\\bin\\test.exe'
이 기능은 str.replace()
및 re.findall()
기능을 모두 사용합니다 . 그것은 모든 발행 수 대체 할 pattern
의를 string
가진 repl
소문자를 구분하지 않는 방식으로.
def replace_all(pattern, repl, string) -> str:
occurences = re.findall(pattern, string, re.IGNORECASE)
for occurence in occurences:
string = string.replace(occurence, repl)
return string
never posted an answer before and this thread is really old but i came up with another sollution and figured i could get your respons, Im not seasoned in Python programming so if there are appearant drawbacks to it, please point them out since its good learning :)
i='I want a hIPpo for my birthday'
key='hippo'
swp='giraffe'
o=(i.lower().split(key))
c=0
p=0
for w in o:
o[c]=i[p:p+len(w)]
p=p+len(key+w)
c+=1
print(swp.join(o))
I was having \t being converted to the escape sequences (scroll a bit down), so I noted that re.sub converts backslashed escaped characters to escape sequences.
To prevent that I wrote the following:
Replace case insensitive.
import re
def ireplace(findtxt, replacetxt, data):
return replacetxt.join( re.compile(findtxt, flags=re.I).split(data) )
Also, if you want it to replace with the escape characters, like the other answers here that are getting the special meaning bashslash characters converted to escape sequences, just decode your find and, or replace string. In Python 3, might have to do something like .decode("unicode_escape") # python3
findtxt = findtxt.decode('string_escape') # python2
replacetxt = replacetxt.decode('string_escape') # python2
data = ireplace(findtxt, replacetxt, data)
Tested in Python 2.7.8
Hope that helps.
참고URL : https://stackoverflow.com/questions/919056/case-insensitive-replace
'IT story' 카테고리의 다른 글
Android 푸시 알림 : 알림에 아이콘이 표시되지 않고 흰색 사각형이 대신 표시됨 (0) | 2020.06.12 |
---|---|
MySQL 열 정의를 변경하는 방법? (0) | 2020.06.12 |
git repo 및 작업 복사본에서 LF eol 강제 실행 (0) | 2020.06.12 |
process.env.NODE_ENV가 정의되지 않았습니다 (0) | 2020.06.12 |
github에서 gem의 특정“커밋”을 얻는 방법은 무엇입니까? (0) | 2020.06.12 |