Splitting and Joining: split(), splitfields(), join(), joinfields()

split(s, [sep], [maxsplit]) and splitfields(s, [sep], [maxsplit]) both split a string into a sequence. With the sep argument you can specify what you want to use for the separator—the default is whitespace (spaces or tabs). The maxsplit optional argument allows you to specify how many items you want to break up; the default is all.

Here, with one line of code, we parse an address containing five fields. (Try to do this with Java, C, Delphi, or Visual Basic—you can't.)

 >>> input_string = "Bill,Gates,123 Main St., WA, 65743" >>> fname, lname, street, state, zip = split(input_string,",") >>> print """ ... Name: %(fname)s %(lname)s ... Street: %(street)s ... %(state)s, %(zip)s""" ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.