Low Orbit Flux Logo 2 D

Python How To Split A String

You are probably looking for a way to split a string using Python. The good news is that this is very easy and there are multiple ways to do it. You can use the split() string method or you could use a regex. The choice is yours.

To split a string in Python just use the following:


list = myString1.split()

Split a string by spaces:


z = "This is a string of text"
x = z.split()

Split using another specified character, for example a comma:


z = "carrots, frogs, rocks, cars, misc"
x = z.split(", ")

Split by “-“ and only grab the first 3 elements:


z = "tree-flower-pool-pizza"
x = z.split("-", 1)

Python Split a String with a Regular Expression ( regex )

You can also split strings using regular expressions. This gives us a bit more flexibility and power.

This example shows how you would split a string by colon “:” characters. It also pre-compiles the regex which would be useful if you were to run this repeatedly in a loop.


import re
p = re.compile(r':')
a = p.split('test test:two two:asdf asdf')

Here is another example showing how you might split a string by the arbitrary pattern “ABC”. In this case we call the split function directly without compiling first instead of using the version that belongs to a compiled regex.


import re
a = re.split("ABC", 'test testABCtwo twoABCasdf asdf')