Splitting Strings


print sentence.split() print entry.split(':') print paragraph.splitlines(1)

The split(separator) and splitlines(keeplineends) methods are provided by Python to split strings into substrings. The split method searches a string, splits it on each occurrence of the separator character, and subdivides it into a list of strings. If no separator character is specified, the split method will split the string at each occurrence of a whitespace character (space, tab, newline, and so on).

The splitlines method splits the string at each newline character into a list of strings. This can be extremely useful when you are parsing a large amount of text. The splitlines method accepts one argument that is a Boolean true or false to determine whether the newline character should be kept.

sentence = "A Simple Sentence." paragraph = "This is a simple paragraph.\n\ It is made up of of multiple\n\ lines of text." entry =   "Name:Brad Dayley:Occupation:Software Engineer" print sentence.split() print entry.split(':') print paragraph.splitlines(1)


split_str.py

['A', 'Simple', 'Sentence.'] ['Name', 'Brad Dayley', 'Occupation',  'Software Engineer'] ['This is a simple paragraph.\n',  'It is made up of of multiple\n',  'lines of text.']


Output from split_str.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net