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


问题内容
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

我知道在第一次迭代中,字符串s只是第一个字符,在这种情况下为大写的“ I”。但是,我尝试使用“ s =”swapchcase()代替它,但是没有用。

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


问题答案:

字符串在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)))

印刷

I like StackOverflow and Python