Capitalize a substring within a string

。_饼干妹妹 提交于 2019-12-11 03:27:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!