I am given the sentence My team is the BeST team at the tournament. as a test case to create create a function
def case_insensitivity(sentence):
return new_sentence
which checks a given sentence for a case insensitive word and replaces the case insensitive word with XXX_
.
i.e.
print(case_insensitivity('My team is the BeST team at the tournament'))
result
'My team is the XXX_ team at the tournament'
What's the best way to do this? casefold()
CodePudding user response:
Assuming we define the target words as having both a lowercase and uppercase beyond the first character, we can try using re.sub
for a regex option:
def case_insensitivity(sentence):
return re.sub(r'\w (?:[A-Z]\w*[a-z]|[a-z]\w*[A-Z])\w*', 'XXX_', sentence)
print(case_insensitivity('My team is the BeST team at the tournament'))
This prints:
My team is the XXX_ team at the tournament
CodePudding user response:
This is my solution (hopefully I understand well your problem):
you split the sentence intro words.
you loop through all the words
you loop through the letters of the words - starting from the second letter of each word.
check if there are any uppercase letters
if you find uppercase letter you give 1 to the have_to_replace variable.
you make the replacement
txt = 'My team is the BeST team at the tournament' x = txt.split() for w in x: have_to_replace = False for l in w[1:]: if l != l.casefold(): have_to_replace = True if have_to_replace: txt = txt.replace(w, 'XXX_', 1) print(txt)
For some reason the Code blocking is not working properly for the first 3 lines (and the last). Sorry for that.