Change/Print results to Uppercase

Question:

I want to change an array from lower case to uppercase and print the result in Python.

In the following x will continue to print in lowercase.

x = ['ab', 'cd']
for i in x:
    i.upper()
print(x)

How do you write the code so x = ['AB', 'CD] when you print for x?

Answers:

list comprehension is best for this.

x = ['ab', 'cd']
x = [i.upper() for i in x]
print(x)
Answered By: mkrana

You need to assign the uppercased characters back to the original string.

x = ['ab', 'cd']

#Loop through x and update element
for idx, item in enumerate(x):
    x[idx] = item.upper()

print(x)

Or by using list comprehension

x = ['ab', 'cd']
x = [item.upper() for item in x]
print(x)

The output will be

['AB', 'CD']
Answered By: Devesh Kumar Singh

Can be done with list comprehensions. These basically in the form of
[function-of-item for item in some-list]

in your case

x = [a,b,c] 
[i.upper() for i in x ]
Answered By: abu

If you don’t know how to use list comprehension then you can write:

x = ['ab', 'cd']

result = [] # create list for upper strings

for i in x:
    upper_i = i.upper() # create upper string
    result.append(upper_i) # add upper string to list

x = result # replace lists

print(x)
Answered By: furas
x = ['ab', 'cd']
x = [i.upper() for i in x]

print(x)

output

['AB', 'CD']
Answered By: sahasrara62
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.