xxxxxxxxxx
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
xxxxxxxxxx
# instead of regular split
>> s = "a,b,c,d"
>> s.split(",")
>> ['a', 'b', 'c', 'd']
# ..split only on last occurrence of ',' in string:
>>> s.mysplit(s, -1)
>>> ['a,b,c', 'd']
xxxxxxxxxx
line_1 = 'This is my line'
# When splitting it looks for spaces in the string and split from there
print(line_1.split()) # Output: ['This', 'is', 'my', 'line']
# Remember several spaces is also considered as one space
line_2 = 'This is my line'
print(line_2.split()) # Output: ['This', 'is', 'my', 'line']
# We can also split the string using a sub-string (you can specify the delimiter)
# Now the spaces are not considered, look at 'm y'
line_3 = 'This,is,m y,line'
print(line_3.split(',')) # Output: ['This', 'is', 'my', 'line']
xxxxxxxxxx
def split(txt, seps):
default_sep = seps[0]
# we skip seps[0] because that's the default separator
for sep in seps[1:]:
txt = txt.replace(sep, default_sep)
return [i.strip() for i in txt.split(default_sep)]
>>> split('ABC ; DEF123,GHI_JKL ; MN OP', (',', ';'))
['ABC', 'DEF123', 'GHI_JKL', 'MN OP']