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

4

Given this list:

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

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

    
asked by anonymous 17.04.2018 / 22:25

2 answers

7

Code:

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

Result:

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

Explanation:

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

See working at Ideone .

    
17.04.2018 / 22:34
1

In addition, when using split to separate the strings in the blanks, you do not need to strip before when the separator is not set as a parameter.

See what documentation says:

  

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

     

If it is not specified or not, a different splitting algorithm is applied: runs of consecutive whitespace are considered 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, by doing var.split() it will separate var in all whitespace and return only the parts that are non-empty strings. Also, a micro-optimization is possible to define the maximum number of separations in the string. Since only the first word in the string will be of interest, there is no reason to separate it in all spaces; just the first. So:

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

Or even use the map function to set 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 output:

Paulo
Fabio
Roberto
    
27.08.2018 / 15:20