Python-Ref > String manipulation > String splitting and joining > Splitting to lines
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Splitting to lines

How to split a long text to individual lines.
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.
Expand/Shrink
  1   text = """This is a long
  2   multiline text, that
  3   we would like to split
  4   to individual lines."""
  5   
  6   # the standard way
  7   print text.split( "\n")
  8   
  9   # using a convenience method
 10   print text.splitlines()
 11   
 12   for line in text.splitlines():
 13     print line
stdout:
['This is a long', 'multiline text, that', 'we would like to split', 'to individual lines.']
['This is a long', 'multiline text, that', 'we would like to split', 'to individual lines.']
This is a long
multiline text, that
we would like to split
to individual lines.
Doba běhu: 14.3 ms
Expand/Shrink
This is an example text in an example file.
It even has
several
lines.
  1   f = file( "example.txt", "r")
  2   text = f.read()
  3   f.close()
  4   
  5   for line in text.splitlines():
  6     print line
stdout:
This is an example text in an example file.
It even has
several
lines.
Doba běhu: 14.1 ms