Print the first three characters of each item in the list which has more than 5 characters

Viewed 56
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for word in items:
   print(word[:3])
#prints the first three characters of each item

def string_k(k, str):
  string = []
  text = str.split(" ")
  for x in text:
    if len(x) > k:
      string.append(x)
  return string
k = 6
str = "Apple, Banana, Cherry, Date, Eggfruit, Fig"
print(string_k(k, str))
#This prints out every item in the list that has more than five characters

This is similar to my first question - i have the two separate codes but i don't understand how to get them together to get the output that i need

3 Answers

You can use filter here.

items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]

for _str in filter(lambda x:len(x)>=5,items):
    print(_str[:3])

Output:

App
Ban
Che
Egg

This should work better than your code.

items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for i in range(0, len(items)):
    if len(i) >= 5:
        print(i[:3])
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for item in items:
  if len(item) >= 5:
    print(item[:3])
Related