将一些小写字母更改为字符串中的大写

Han*_* N. 10 python string python-3.x uppercase

index = [0, 2, 5]
s = "I am like stackoverflow-python"
for i in index:
        s = s[i].upper()
print(s)

IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)

据我所知,在第一次迭代中,字符串s变为第一个字符,在这种特殊情况下为大写"I".但是,我试图在没有"s ="的情况下使用swapchcase()它,而是使用它,但它没有用.

基本上,我正在尝试s使用Python 3.X将索引字母打印为大写的字符串

Sve*_*ach 19

字符串在Python中是不可变的,因此您需要创建一个新的字符串对象.一种方法:

indices = set([0, 7, 12, 25])
s = "i like stackoverflow and python"
print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))
Run Code Online (Sandbox Code Playgroud)

印花

I like StackOverflow and Python
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ton 5

这是我的解决方案。它不会遍历每个字符,但是我不确定将字符串转换为列表然后再转换为字符串是否更有效率。

>>> indexes = set((0, 7, 12, 25))
>>> chars = list('i like stackoverflow and python')
>>> for i in indexes:
...     chars[i] = chars[i].upper()
... 
>>> string = ''.join(chars)
>>> string
'I like StackOverflow and Python'
Run Code Online (Sandbox Code Playgroud)