how to print words with 7 or more than 7 letters in python

Asked

Viewed 73 times

-3

I have to make a code that prints names with more than 7 letters I’m using the pycharm my code is as follows::

nome = input("Digite os nomes separados por vírgula: ")
nomes = nome.split(',')

def imprime_nome_com_7_letras(nomes):
    print("nomes com mais de 7 letras")
    print([nome for nome in nomes if len(nome) == 7])

imprime_nome_com_7_letras(nomes)

if anyone can help me thank you.

  • 2

    What’s the doubt? The code you wrote even makes sense, the only detail is that it is displaying only names with EXACTLY 7 letters, as it did len(nome) == 7, but that is not what is requested in the.

  • Your code will receive more than one name. The method split() returns a list, where each item in that list is a word. For you to validate item by item from a list, for nome in nomes: to check the size of the string if len(nome) > 7: print(nome)

  • Although the function is not implemented according to Python standards, if you replace len(nome) == 7 for len(nome) >= 7, you will already have the desired result. However, I suggest studying a little more about the function structures.

2 answers

0

If you want to filter a sequence by one criterion, use the built-in function filter() who according to his documentation:

filter(function, iterable)
Build an iterator from the iterable elements for which Function returns true. iterable can be a sequence, a container that supports iteration, or an iterator.

nomes = "Alexandre,Eduardo,Henrique,Murilo,Theo,André,Enrico,Henry,Nathan,Thiago,Antônio,Enzo,Ian,Otávio,Thomas,Augusto,Erick,Isaac,Pietrp,Vicente,Letícia,Maya,Sara,Yasmin"
nomes = nomes.split(",")        
    
print(*filter(lambda nome: len(nome) >= 7, nomes), sep="\n" )

Resulting:

Alexandre
Eduardo
Henrique
Antônio
Augusto
Vicente
Letícia

Test in ideone.

0


It is only to do a go in each name and print it if you obey the rule by placing an if inside it:

def imprime_nome_com_7_letras(nomes):
   print("nomes com mais de 7 letras")
   for nome in nomes:
    if(len(nome) >= 7):
        print(nome)
  • 1

    for i in range(len(nomes)), ideal would be to avoid this kind of loop to go through the list. Best would be for nome in nomes.

  • I agree, Woss. It’s been a while since I’ve touched python and I forget sometimes. Thanks I’ll fix it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.