sexta-feira, 18 de setembro de 2015

Python - Exemplos do comando Split e Join

Fonte: http://www.webmasterwords.com/python-split-and-join-examples

sentence = "the cat sat on the mat"
print sentence.split()
['the', 'cat', 'sat', 'on', 'the', 'mat']
Split words separated by a single character:
sentence = "the,cat,sat,on,the,mat"
print sentence.split(',')
['the', 'cat', 'sat', 'on', 'the', 'mat']
Split words separated by a string:
sentence = "theSPACEcatSPACEsatSPACEonSPACEtheSPACEmat"
print sentence.split('SPACE')
['the', 'cat', 'sat', 'on', 'the', 'mat']
Split only the first two words in a comma separated string
sentence = "the,cat,sat,on,the,mat"
print sentence.split(',',2)
['the', 'cat', 'sat,on,the,mat']
Python Join
Join uses a sligthly difference implmentation to what you might be used to. The character that joins the elements is the one upon which the function is called
Joining an array with spaces
' '.join(['the', 'cat', 'sat', 'on', 'the', 'mat'])
'the cat sat on the mat'
Joining an array with commas
','.join(['the', 'cat', 'sat', 'on', 'the', 'mat'])
'the,cat,sat,on,the,mat'

Nenhum comentário: