将字符串中的某些小写字母改为大写
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()
,结果却没有成功。
基本上,我是想用 Python 3.X 打印出字符串 s
,让索引位置的字母变成大写。
2 个回答
7
这是我的解决方案。它并不是逐个字符地处理,但我不确定把字符串转换成列表再转换回字符串是否更有效率。
>>> 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'
22
在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