Python-Ref > String manipulation > String splitting and joining > Whitespace normalization

Klíčová slova
Knihovní funkce

Whitespace normalization

The split and join methods may be used for efficient whitespace normalization.
Spliting a string and using a single whitespace to join it is the fastest way to normalize its whitespace, that is replacing all consecutive whitespace characters with a single space and removing leading and trailing whitespace.
  1   text = "    Hello    World,    I       am   here.  "
  3   a = text.split()  # at first we split the string, removing all whitespace
  4   print a
  5   b = ' '.join( a)  # the we put it together using a single space
  6   print b
  8   print ' '.join( text.split())   # this is the shorter way to do it
['Hello', 'World,', 'I', 'am', 'here.']
Hello World, I am here.
Hello World, I am here.
Doba běhu: 13.7 ms