Python – Split strings

In this post we will touch base on splitting strings in Python, the term string in Python refers to a sequence of Unicode characters whether that be a collection of letters from the alphabet or a series of numbers.

An example of a string can be seen below.

someString = "Welcome to Scriptopia!"

The splitting of a string would mean to break it down in to smaller chunks in the form of a list. Using the split() method you can define your separator i.e. split a string each time a full stop is found. If no separator is defined the split method will default to every instance of whitespace found.

The split() method will always return a list, if you are interested in iterating a list click here.

In the snippet of code below a separator is not defined.

someString = "Welcome to Scriptopia!"

split = someString.split()

print(split)

The above would output the following.

['Welcome', 'to', 'Scriptopia!']
>>> 

In the snippet of code below we will define our separator as a comma.

someString = "Welcome to Scriptopia, subscribe for more."

split = someString.split(", ")

print(split)

The above would output the following.

['Welcome to Scriptopia', 'subscribe for more.']
>>> 

Leave a Reply