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