#345 · Strings · Advanced · 115 XP · about 20 min
A thoughtful find-and-replace changes "Cat" to "Dog", "CAT" to "DOG" and "cat" to "dog", so the text keeps its style. Write replace_keep_case(text, old, new) that replaces every occurrence of the phrase old in text with the phrase new, written in the style of that occurrence.
old and new are one or more words separated by single spaces, and a word is a run of English letters.text that equals old when case is ignored, with no letter right before it and no letter right after it.Each replacement copies the style of the occurrence it replaces. Use the first of these rules that fits:
new in lowercase.new in capitals.new that way.new exactly as it was given.replace_keep_case('Cat and cat and CAT', 'cat', 'dog') # returns 'Dog and dog and DOG' replace_keep_case('Concatenate the cat.', 'cat', 'dog') # returns 'Concatenate the dog.' replace_keep_case('I love New York. NEW YORK never sleeps!', 'new york', 'los angeles') # returns 'I love Los Angeles. LOS ANGELES never sleeps!' replace_keep_case('My cAt', 'cat', 'iPhone') # returns 'My iPhone'
A single capital letter such as "I" counts as a capitalized word, because capitals need at least two letters.
text has at most 200,000 characters: English letters, spaces and punctuation, with no digits or underscores.old and new have 1 to 5 words each.First solves only, ranked by stars and then time.