简体   繁体   中英

How can I make my list items first letter all capital

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

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))
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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM