In short, the split()
methods allows you to easily split a string into a list. In this guide, we’ll see how to split a string in Python.
Split a String in Python with split()
By default, every word is a list item. To split a string in python we use the split()
method.
In the following example, we will define text
variable, use the split()
method to split it, and then we will print it:
text = "Linux is awesome"
x = text.split()
print(x)
output
['Linux', 'is', 'awesome']
Custom separator
By default the separator when using the split method, is whitespace, but, we can specify it. In the following example we’ll specify that at each slash (/
) we will make a split()
:
text = "linux/is/so/good"
v = text.split("/")
print(v)
output
['linux', 'is', 'so', 'good']
Custom amount of Splits
By default value for the amount of splits is -1, which is all occurrences. We can specify the amount of splits we’d like to do with specifying the maxsplit
:
string.split(separator, maxsplit)
In the following example, we’ll set the maxsplit
to 1
, meaning that it will only split the list into two elements:
text = "linux/is/so/good"
v = text.split("/", 1)
print(v)
output
['linux', 'is/so/good']
Summary
This guide focused on how you can easily split a string in python. As well as specify the separator, and amount of splits.