Splitting a string in Python
Start your free 7-days trial now!
To split a string using whitespace as the delimiter:
s ='this is a sentence's.split()['this', 'is', 'a', 'sentence']
The default separator is whitespace hence the string is split into four parts and returned as elements of a list.
To split using a delimiter other than whitespace:
s ='this,is,a,sentence's.split(',')['this', 'is', 'a', 'sentence']
Split by line break
Unix OS (including Mac) uses
\n (LF) while Windows OS uses
\r\n (CR + LF) for line breaks. As
str.split(~) only takes on a single
sep argument, it is recommended to use
str.splitlines(~) to split by line break:
s = 'hi\nthis\r\nis \nskytowner's.splitlines()['hi', 'this', 'is ', 'skytowner']