change some lowercase letters to uppercase in string

感情迁移 提交于 2019-12-19 05:35:02

问题


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

I understand that in the first iteration the string, s, become just the first character, an uppercase "I" in this particular case. But, I have tried to do it without the "s = " , using swapchcase() instead, but it's not working.

Basically, I'm trying to print the s string with the index letters as uppercase using Python 3.X


回答1:


Strings are immutable in Python, so you need to create a new string object. One way to do it:

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)))

printing

I like StackOverflow and Python



回答2:


Here is my solution. It doesn't iterate over every character, but I'm not sure if converting the string to a list and back to a string is any more efficient.

>>> 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'


来源:https://stackoverflow.com/questions/8217650/change-some-lowercase-letters-to-uppercase-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!