-3

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?

Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
  • you have to add result `i.upper()` to new list and print this new list. Or print it directly in loop `print(i.upper())` – furas May 03 '19 at 05:22
  • `print([i.upper() for i in x])` – Stephen Rauch May 03 '19 at 05:23
  • Do you want to do it in-place or you want to preserve the original list @GeneralCorrespondence ? – Devesh Kumar Singh May 03 '19 at 06:43
  • Possible duplicate of [Convert a Python list with strings all to lowercase or uppercase](https://stackoverflow.com/questions/1801668/convert-a-python-list-with-strings-all-to-lowercase-or-uppercase) – DJK May 03 '19 at 17:52

5 Answers5

3

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']
Devesh Kumar Singh
  • 19,767
  • 5
  • 18
  • 37
1

list comprehension is best for this.

x = ['ab', 'cd']
x = [i.upper() for i in x]
print(x)
mkrana
  • 402
  • 4
  • 10
0
x = ['ab', 'cd']
x = [i.upper() for i in x]

print(x)

output

['AB', 'CD']
sahasrara62
  • 7,680
  • 2
  • 24
  • 37
-1

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 ]
abu
  • 11
  • 2
-2

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)
furas
  • 119,752
  • 10
  • 94
  • 135
  • You can avoid the extra list by doing it in place! @furas – Devesh Kumar Singh May 03 '19 at 07:36
  • @DeveshKumarSingh I could avoid it but OP is beginner and I specially rewrite it in many steps. And probably OP choose my answer because it is not in one line. – furas May 03 '19 at 07:41
  • OP is already chosen your answer! I wonder the downvotes are due to the simplicity but extra usage of space @furas ! – Devesh Kumar Singh May 03 '19 at 07:43
  • 1
    @DeveshKumarSingh I think it is downvoted because of simplicity. But all these steps and even empty lines are to make it more useful for beginner. – furas May 03 '19 at 07:47