.split() |
>>> s =
'Hi,there,Fred' >>> things = s.split(',') >>> print(things) ['Hi', 'there', 'Fred'] >>> s2 = 'Hi<duck>there<duck>Fred' >>> bleep = s2.split('<duck>') >>> print(bleep) ['Hi', 'there', 'Fred'] # look at this one carefully... >>> flap = s2.split('<') >>> print(flap) ['Hi', 'duck>there', 'duck>Fred'] # useful for splitting a multi-line string into a list of lines >>> s3 = '''first line second third''' >>> print(s3.split('\n')) ['first line', 'second', 'third'] # but be careful about a trailing blank line... look at the difference between s3 and s4: the extra '\n' at the end of s4 >>> s4 = '''first line second third ''' >>> print(s4.split('\n')) ['first line', 'second', 'third', ''] # If you don't give .split() an argument, it assumes that the separator is one or more "whitespace" characters (spaces, newlines, tabs) # and treats multiple adjacent whitespace characters as a single separator >>> s5 = ' Hi there Fred ' >>> print(s5.split()) ['Hi', 'there', 'Fred'] >>> s6 = '''Hi there Fred ''' >>> print(s6.split()) ['Hi', 'there', 'Fred'] |
.join() |
# What Python hath torn asunder let each man join together. # Take a list of words/strings and join them together into a string with a separator separating the words >>> L = ['Hi', 'there', 'Fred'] >>> s1 = '<yo>'.join(L) >>> print(s1) Hi<yo>there<yo>Fred >>> print(' '.join(L)) Hi there Fred >>> print('\n'.join(L)) Hi there Fred |