>>> import string >>> str = 'one two three four five' >>> string.split(str) ['one', 'two', 'three', 'four', 'five'] >>> string.split(str,' ') ['one', 'two', '', '', 'three', 'four', '', '', '', 'five']In the first (default) case, any number of blanks serves as a separator, whereas when a blank is provided as the separator character, fields separated by multiple blanks produce empty strings in the output list.
Finally, an optional third argument (maxsplit) limits the number of times split will break apart its input string. If more separators are present in the input string than the maxsplit argument implies, the remainder of the string is returned as the final element of the list. For example to split a string into a list with the first word as the first element, and the remainder of the string as the second element, it suffices to call split with maxsplit set to 1:
>>> who = 'we are the knights who say ni' >>> string.split(who) ['we', 'are', 'the', 'knights', 'who', 'say', 'ni'] >>> string.split(who,' ',1) ['we', 'are the knights who say ni']
The function join provides the opposite functionality of split. It accepts a sequence of strings, and joins them together, returning a single string. By default, a blank is inserted between each of the original strings; the optional named argument sep allows you to provide an alternative string to be used as a separator. As a simple example of the join function, consider producing comma-separated data suitable for input to a spreadsheet program.
>>> import string >>> values = [120.45,200.30,150.60,199.95,260.50] >>> print string.join(map(str,values),',') 120.45,200.3,150.6,199.95,260.5Since the first argument to join must be a sequence of strings, the map function was used to convert each element of the values list to a string.
Three functions are provided in the string module for removing whitespace from strings: lstrip, rstrip and strip which removing leading, trailing and both leading and trailing whitespace from a string, respectively. Each of the functions accepts a string and returns the stripped string.
A variety of functions dealing with capitalization are contained in the string module. The capitalize function returns its input string with the first letter capitalized. The capwords function capitalizes the first letter of each word in a string, replaces multiple blanks between words with a single blank, and strips leading and trailing whitespace. The swapcase function accepts a string and returns a string with the case of each character in the original string reversed (uppercase becomes lowercase and vice versa). The upper function returns a string with all the characters of its input string converted to uppercase; the lower function converts all characters to lowercase.