将字符串中的子字符串大写 [英] Capitalize a substring within a string
本文介绍了将字符串中的子字符串大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建类似的东西:
string:你今天过得怎么样?子串:o>>>今天怎么样?
我已经编写了其余的代码(提示输入字符串等),我只是坚持必须将字符串中的子字符串大写.
解决方案
>>>s='你今天过得好吗?>>>sub_s='o'>>>s.replace(sub_s, sub_s.upper())'今天怎么样?'
如果您只想更改一些(即第二个),一个衬里,则可能会变得更加复杂:
<预><代码>>>>''.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)])'今天怎么样?'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.
解决方案
>>> 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?'
这篇关于将字符串中的子字符串大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文