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

时间:2011-11-21 19:49:42

标签: 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

据我所知,在第一次迭代中,字符串s只是第一个字符,在这种特殊情况下是大写的“I”。但是,我试图在没有“s =”的情况下使用swapchcase()代替它,但它不起作用。

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

2 个答案:

答案 0 :(得分: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)))

印刷

I like StackOverflow and Python

答案 1 :(得分:4)

这是我的解决方案。它不会迭代每个字符,但我不确定是否将字符串转换为列表并返回字符串更有效。

>>> 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'
相关问题