How to make the inversion of what is received by adding a comma?

0

Program that receives a name through keyboard and should print the surname, first name and other abbreviated names eg receives "Luis Costa Santos" and returns "Santos, Luis C."

lista = []
nome = ''
answer = ''
i = 0

while answer != 'n':
    nome = str(input('ponha o seu nome: '))
    lista.append(nome)
    answer = str(input('deseja continuar? s ou n: '))
    if answer == 's':
        i += 1
    else:
        break

print(lista)
    
asked by anonymous 01.10.2018 / 22:03

2 answers

4

You will need to follow these steps:

  • Break the full name by spaces (using str.split() for example)
  • separate the last name ( list.pop() ) and keep unchanged
  • separate the first name ( list.pop(0) ) and keep unchanged
  • get only the first letter of the rest of the name
  • concatenate the response
  • Example:

    def converte_nome(nome):
        nome = nome.split()
    
        primeiro_nome = nome.pop(0)
        sobrenome = nome.pop()
    
        restante = [primeiro_nome] + [n[0] + "." for n in nome]
        restante = " ".join(restante)
    
        return f"{sobrenome}, {restante}"
    
    print(converte_nome('Luis Carlos Costa'))
    # Costa, Luis C.
    print(converte_nome('Fernando Sávio Rosback Dominguez'))
    # Dominguez, Fernando S. R.
    print(converte_nome('João Silva'))
    # Silva, João
    

    Code working .

        
    01.10.2018 / 22:21
    2

    The code you passed has almost nothing to do with the question - it only reads the names and adds them to a list!

    This example takes a name that is in the nome variable and applies what you did. Initially it divides the whole name into separate words, and then treats each word separately:

    palavras = nome.split()
    novo_nome = ' '.join([  #monta o novo nome, composto de:
        palavras[-1] + ',', # ultimo nome seguido de virgula
        palavras[0],        # primeiro nome
    ] + [palavra[0] + '.'   # primeira letra seguida de ponto
        for palavra in palavras[1:-1]]) # dos demais nomes do meio
    

    Testing, with nome = "Luis Costa Santos" , the result is expected:

    Santos, Luis C.
    
        
    01.10.2018 / 22:21