So far I've come up with the method below but my question is is there a shorter method out there that has the same result?
My Code :
input_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str = "stuff"
replacer_str = "banana"
print input_str
# prints: myStrIngFullOfStUfFiWannAReplaCE_StUfFs
if replace_str.lower() in input_str.lower(): # Check if even in the string
begin_index = input_str.lower().find( replace_str )
end_index = begin_index + len( replace_str )
replace_section = input_str[ begin_index : end_index ]
case_list = []
for char in replace_section: # Get cases of characters in the section to be replaced
case_list.append( char.istitle() )
while len( replacer_str ) > len(case_list):
case_list += case_list
sameCase_replacer_str = "" # Set match the replacer string's case to the replace
replacer_str = replacer_str.lower()
for index in range( len(replacer_str) ):
char = replacer_str[ index ]
case = case_list[ index ]
if case == True:
char = char.title()
sameCase_replacer_str += char
input_str = input_str.replace( replace_section , sameCase_replacer_str )
print input_str
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs
I'd use something like this:
Example output:
Notes:
You can pass
flags=re.I
tore.sub()
to ignore-caseFrom the code it's obvious that the case pattern for replacement is made from the match case pattern by repeating it over (so
StufF -> BanaNA
). Bearing this in mind I would first find case pattern for the whole string, and then bring the string to desired case: