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
Wow I was trying to remember the name of the method for taking out the spaces, and I just remembered
trim()
rs– NoobSaibot
@wmsouza I also remembered thanks to IDE because when I typed
tr
to writetrim
he suggested to mestrip
rsrs– Math
thanks , sometimes a simple thing becomes complicated , I thought of several things , but did not know how to apply in practice .
– Cleomir Santos
I commented in my reply on the need for
strip
in that case :D– Woss