How to separate only the first word of each string from a list?

Asked

Viewed 2,728 times

5

Given that list :

nomes = [ " Paulo Ricardo " , " Fabio Junior " , " Roberto Carlos " ]

How do I create a new list, separating the last name from the last name and only adding the last name without the last name in this new list, using list comprehension, please.

2 answers

9


Code:

nomes = [" Paulo Ricardo ", " Fabio Junior ", " Roberto Carlos "]
n = [nome.strip().split(' ')[0] for nome in nomes]
print(n)

Upshot:

['Paulo', 'Fabio', 'Roberto']

Explanation:

strip() to take out the spaces before and after each element, split(' ') to separate the elements by delimiting them by a space, [0] to take the first element of the split(), in case only takes the first name, for to iterate element by element nomes, all this within a list comprehension delimited by [].

See working on Ideone.

  • Wow I was trying to remember the name of the method for taking out the spaces, and I just remembered trim() rs

  • @wmsouza I also remembered thanks to IDE because when I typed tr to write trim he suggested to me strip rsrs

  • thanks , sometimes a simple thing becomes complicated , I thought of several things , but did not know how to apply in practice .

  • I commented in my reply on the need for strip in that case :D

1

To complement, by using the split to separate the strings in the blanks, it is not necessary to strip before when the separator is not defined as a parameter.

See what the documentation says:

str.split(sep=None, maxsplit=-1)

If Sep is not specified or is None, a Different splitting Algorithm is Applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no Empty strings at the start or end if the string has Leading or trailing whitespace.

That is, in doing var.split() he will part var in all whitespace and will return only the parts that are not empty strings. Also, a micro-optimization possible is to set the maximum number of separations in the string. As only the first word of the string will be of interest, there is no reason to separate it in all spaces; just the first one. So:

primeiros_nomes = [nome.split(None, 1)[0] for nome in nomes]  # ['Paulo', 'Fabio', 'Roberto']

Or even use the function map to define a generator instead of creating another list:

def pegar_primeiro_nome(nome):
    return nome.split(None, 1)[0]

primeiros_nomes = map(pegar_primeiro_nome, nomes)

for nome in primeiros_nomes:
    print(nome)

Producing the output:

Paulo
Fabio
Roberto
  • great answer!

Browser other questions tagged

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