Python-Ref > String manipulation > String splitting and joining > Split and join
 
 

<-^^->
Moduly
Knihovní funkce

Split and join

split and join are often used together.
Expand/Shrink
  1   text = "Hello World, I am here."
  2   
  3   words = text.split()   # we split the string
  4   print '*'.join( words)   # and put it together again
  5   print '   '.join( words)
  6   print ''.join( words)
stdout:
Hello*World,*I*am*here.
Hello   World,   I   am   here.
HelloWorld,Iamhere.
Doba běhu: 15.1 ms
The split and join operations are symmetric, so splitting a string and joining it back using the same string leads to the original being restored.
Expand/Shrink
  1   text = "Hello World, I am here."
  2   
  3   words = text.split(" ")
  4   print ' '.join( words)
  5   
  6   print "l".join( text.split( "l"))
  7   
  8   # the symmetry holds for every possible split character
  9   import string
 10   for letter in string.ascii_lowercase:
 11     if letter.join( text.split( letter)) == text:
 12       print "OK", letter
 13     else:
 14       print "Error", letter
 15   
 16   # the symmetry breaks only if split without arguments is used
 17   # because then all whitespace is discarded
 18   text = "Hello  World, \t I am here."
 19   print text
 20   result = ' '.join( text.split())
 21   print result
 22   print result == text
stdout:
Hello World, I am here.
Hello World, I am here.
OK a
OK b
OK c
OK d
OK e
OK f
OK g
OK h
OK i
OK j
OK k
OK l
OK m
OK n
OK o
OK p
OK q
OK r
OK s
OK t
OK u
OK v
OK w
OK x
OK y
OK z
Hello  World, 	 I am here.
Hello World, I am here.
False
Doba běhu: 16.3 ms