Python – How to split a String

Python – How to split a String

Few examples to show you how to split a String into a List in Python.

1. Split by whitespace

By default, split() takes whitespace as the delimiter.

alphabet = "a b c d e f g"
data = alphabet.split() #split string into a list

for temp in data:
    print temp

Output

a
b
c
d
e
f
g

2. Split + maxsplit

Split by first 2 whitespace only.

alphabet = "a b c d e f g"
data = alphabet.split(" ",2) #maxsplit

for temp in data:
    print temp

Output

a
b
c d e f g

3. Split by #

Yet another example.

url = "mkyong.com#100#2015-10-1"
data = url.split("#")

print len(data) #3
print data[0]  # mkyong.com
print data[1]  # 100
print data[2]  # 2015-10-1

for temp in data:
    print temp

Output

3
mkyong.com
100
2015-10-1
mkyong.com
100
2015-10-1

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *