Home > other >  How to convert a single item in a list to .lower()
How to convert a single item in a list to .lower()

Time:07-05

How do I convert single item in a list by using for loop? I want program to recognize plane not being in lowercase and making it lowercase.

vehicles = ['car', 'bicycle', 'Plane',]

for vehicle in vehicles:
    if vehicle == vehicle.lower():
        print(f"{vehicle.title()} is in lowercase")
    else:
        print(f"Vehicle is not in lowercase: {vehicle}")

I tried with:

if vehicle in vehicles != vehicle.lower():
    vehicle = vehicle.lower()

print(vehicles)

But when I print list again, it still shows plane with first capital letter.

Edit: Sorry for some confusion, I added "print(f"{vehicle.title()} is in lowercase")" just for esthetics. What I want, is to make program recognize string not being in lowercase and then modify that string in a list, then when list in being printed again, it shows "Plane" in list as "plane".

CodePudding user response:

Your first bit of code correctly detects whether a string is not lowercased, but you print the non-lowercased version (using vehicle.title()). You don't actually need to detect whether it's lowercase or not. Just lowercase them all --- it's cheap enough.

vehicles = [vehicle.lower() for vehicle in vehicles]

CodePudding user response:

It sounds like you simply to make everything lowercase in that case you could use list comprehension:

vehicles_lower = [v.lower() for v in vehicles]
print(vehicles_lower)

CodePudding user response:

Your question is a duplicate of Change value of currently iterated element in list

You have to change your for loop like this if you want to change the list:

a_list = ["a", "b", "c"]

for i in range(len(a_list)):
    a_list[i] = a_list[i]   a_list[i]

print(a_list)

In his answer, @erip provided yet another syntax to do it by assigning the result back to the list.

  • Related