Skip to content Skip to sidebar Skip to footer

Capitalize A Substring Within A String

I'm trying to create something like: string: How do you do today? substring: o >>> hOw dO yOu dO tOday? I've already written the rest of the code (prompting for strings

Solution 1:

>>> s='How do you do today?'
>>> sub_s='o'
>>> s.replace(sub_s, sub_s.upper())
'HOw dO yOu dO tOday?'

And can get more complicated if you only want to change some (i.e., the 2nd one), one liner:

>>> ''.join([item.upper() if i==[idx for idx, w in enumerate(s) if w==sub_s][1] else item for i, item in enumerate(s)])
'How dO you do today?'

Post a Comment for "Capitalize A Substring Within A String"