Sometimes you may need to split a string by delimiter to process it further. Python provides split() function for this purpose. In this article, we will look at how to split string by delimiter in python.
How to Split String by Delimiter in Python
Here is the syntax of split() function that allows you to split string by delimiter.
You need to call split() function on the string variable or literal and specify the delimiter to be used for splitting. You may optionally specify maxsplit number, that is the maximum number of splits to be done. If it is not provided then python will split your string into as many as applicable. The result of split() is a list of strings.
Please note, if you do not specify the delimiter, then python will assume space character as the default delimiter.
Let us look at a few examples to split string.
text = "a b c" text.split() ['a', 'b', 'c'] text = "a b c d" text.split() ['a','b','c','d']
In the first example, note that we have not used any delimiter, yet python split the string by space character. In the second example, we have continuous spaces in our string still python treats them as single delimiter.
Here are some example of using split function with commonly used delimiters like space, comma, hash
text = "a,b,c" text.split(',') ['a', 'b', 'c'] text = "a#b#c" text.split('#') ['a', 'b', 'c']
You can use any character or string as delimiter. Here is an example using other characters and strings as delimiters.
text = "atbtct" text.split('t') ['a', 'b', 'c'] text = "good day bad day" text.split("day") ['good ', ' bad ', '']
You may also use string literal instead of string variable, with split function. Here are a couple of examples.
"a b c".split() ['a','b','c'] "good morning".split() ['good','morning']
So we far, we have omitted using maxsplit option. Now we will look at a few examples using maxsplit number too.
text = "a b c" text.split(' ',1) ['a', 'b c'] "d,e,f".split(',',2) ['d','e','f']
In the above example, we have used maxsplit option 1 to split the string once. When you specify maxsplit option, python will split your string that many number of times and then leave the remaining part of string unchanged, as you can see above. We specified maxsplit option as 1, so python split the string once and then kept ‘b c’ string as unchanged. You may also use string literals as you can see above.
In this article, we have looked at how to split string by delimiter in python and also looked at different use cases for it. This is generally used as a part of larger program or application such as for splitting urls, or list of items concatenated into single string.