¿Cuál es la manera más fácil de hacer un insensible a mayúsculas- string replacement
en Python?
Respuestas
¿Demasiados anuncios?El string
tipo no es compatible con esta. Usted es probablemente mejor usar la expresión regular sub método con el re.IGNORECASE opción.
>>> 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'
Unknown
Puntos
22789
viebel
Puntos
1990
Muy simple, en una sola línea:
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'
O bien, utilizar la opcion de "banderas" argumento:
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'
rsmoorthy
Puntos
830
Continuando en bFloch la respuesta, esta función va a cambiar no una, sino todas las apariciones de lo viejo con lo nuevo - en un caso insensible de la moda.
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(old)
return text
bFloch
Puntos
61