python how to uppercase some characters in string

前端 未结 9 1397
北荒
北荒 2021-01-21 17:51

Here is what I want to do but doesn\'t work:

mystring = \"hello world\"
toUpper = [\'a\', \'e\', \'i\', \'o\', \'u\', \'y\']
array = list(mystring)

for c in arr         


        
9条回答
  •  礼貌的吻别
    2021-01-21 18:14

    You are not making changes to the original list. You are making changes only to the loop variable c. As a workaround you can try using enumerate.

    mystring = "hello world"
    toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
    array = list(mystring)
    
    for i,c in enumerate(array):
        if c in toUpper:
            array[i] = c.upper()
    
    print(array) 
    

    Output

    ['h', 'E', 'l', 'l', 'O', ' ', 'w', 'O', 'r', 'l', 'd']
    

    Note: If you want hEllO wOrld as the answer, you might as well use join as in ''.join(array)

提交回复
热议问题