Search code examples
pythonuppercase

why the output of this code is the same in the array?


I saw this code on YouTube. The code should turn all lower case strings (ab ,cd) into upper case string but when I tried this code the output was the same as the array without change. I want know what is going on behind the scenes.

  x = ['ab', 'cd'] 

    for i in x: 
    i.upper()
    print(i)

Solution

  • upper() returns the uppercase of the string it's called on, but does not modify that string. So you're calling upper(), but then ignoring its return value.

    You could capture the return value in a variable and then print it:

    for i in x:
        u = i.upper()
        print(u)
    

    Or just print it directly:

    for i in x:
        print(i.upper())