How can I make my list items first letter all capital

Viewed 59

Im trying to learn python little little in my free time and Im messing around with lists right now. But I cant seem to make my list all capital. My list got some random items random names of my friends and some of their first letter is capital but some of them not. I want to make all of them capital with "title()" command but I cant imply it to a list do you know how can I do it. Here is my code if you want to check it its a little messy though.


#Yemeğe davet edilecekler
guests = ["azra", "demir", "tümay", "zeynep",]
invite_message = "cumartesi yemek düzenliyorum sende gel"
print(f"{guests[0].title()} {invite_message}\n{guests[1].title()} {invite_message}\n{guests[2].title()} {invite_message}")
gelemeyen1 = guests.pop(1)
gelemeyen2 = guests.pop(2)
print(f"Gelemeyenler: {gelemeyen1.title()}, {gelemeyen2.title()}")
print(f"Gelenler: {guests[0].title()}, {guests[1].title()}")
print(f"Daha büyük bir masa buldum {guests[0].title()}, {guests[1].title()} ")
guests.insert(0,"Harun")
guests.insert(1,"Bahar")
guests.append("Deniz")

print(f"{guests[0]}, {guests[1]}, {guests[2].title()}, {guests[3].title()}")

I did all of them one by one but its not an efficient way even though right now it works it will be hard to do it when my list is a long one

4 Answers

To apply your .title() method to each string in your list, you will need to iterate (loop) through that list. The easiest way to do this as a for loop:

names = ["john", "armin", "sarai"]
capitalized_names = []
for name in names:
  capitalized_names.append(name.title())

You can also do this in a single line with a list comprehension:

names = ["john", "armin", "sarai"]
capitalized_names = [name.title() for name in names]
list(map(str.title, YOUR_LIST))

here i defined a function named 'cap', name is passed to cap, then function capitalize the name then give output. i defined this function to use it later. map is used to apply the function to list or any collections, then i have used the function cap to all the items in guests, then i have converted the map into list by using list() then printed it. you can understand it better by doing small modifications and observing them

guests = ["azra", "demir", "tümay", "zeynep"]
def cap(name):
      return name.capitalize()
print(list(map(cap,guests)))

I think this will work for you.

Try this. It uses map:

new_list = list(map(str.title, guests))

Which is equivalent to using a list comprehension:

new_list = [item.title() for item in guests]
Related