4.8 Splitting and stripping
Suppose you have the text
text = " SPECIAL # SALE # TODAY "
and you want to break it into a list containing the three words. First, use split to break the string at the hash marks.
text.split('#')
[' SPECIAL ', ' SALE ', ' TODAY ']
Second, remove the whitespace from the left and right of each word with strip. In one line:
[word.strip() for word in text.split('#')]
['SPECIAL', 'SALE', 'TODAY']
Exercise 4.6
Try to rewrite strip using
replace. Does it work for embedded spaces as in "
How are you? "
?
lstrip and rstrip remove the white space from only the left and right sides, respectively.
[word.lstrip() for word in text.split('#')]
['SPECIAL ', 'SALE ', 'TODAY ...