简体   繁体   中英

how to print first letter of each element in list

I am trying to print out the first letter of each element in my list. I have split my list into seperate variables for each element, and then use a for loop to go through each element.

This is my code:

fish = ["flounder", "sole", "blue cod", "snapper", "terakihi", "john dory", "red cod"]
a, b, c, d, e, f, g = fish

for i in range(len(fish)):
    print(fish[i[0:1]])

This is what I want my code to do:

f
s
b
s
t
j
r

You need to change it to be print(fish[i][0:1]) so you take the first character instead of trying to do something to the int i .

The slice is also unnecessary. If you only want the first element print(fish[i][0]) is enough.

You dont need to use range to iterate over the index values. you can instead just iterate over the list storing the next elment of the list in the variable on each iteration of the loop. Then you just take the first letter from that variable.

fish = ["flounder", "sole", "blue cod", "snapper", "terakihi", "john dory", "red cod"]

for fishy in fish:
    print(fishy[0])
firstLetters = [a[0] for a in fish]
for letter in firstLetters:
    print(letter)

Store the first letters of each word in a list and print them using a loop.

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