问题
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 etc.), I am just stuck on having to capitalize the substring within the string.
回答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?'
来源:https://stackoverflow.com/questions/21152525/capitalize-a-substring-within-a-string