In this tutorial, we will learn how to use the split() function in Python. Splitting a string is a useful operation when you have data stored in the form of text that needs to be processed or analyzed.
The split() function allows you to break a string into a list of substrings based on a specified delimiter.
Step 1: Understanding the split() function
The split() function is a built-in method in Python that splits a string into a list of words based on the specified separator (or delimiter). If no separator is provided, it uses white spaces by default. The syntax for the split() function is as follows:
1 |
string.split(separator, maxsplit) |
Here, separator
is the delimiter upon which to split the string. If not specified, it defaults to whitespace. The maxsplit
parameter is optional, and if provided, it defines the maximum number of splits. If not specified or set to -1, the string will be split into as many substrings as possible.
Step 2: Using split() without parameters
To split a string using white spaces (default behavior), call the split() function without providing any parameters. For example:
1 2 3 |
text = "Learn to use the split function in Python" words = text.split() print(words) |
The output will be:
['Learn', 'to', 'use', 'the', 'split', 'function', 'in', 'Python']
Here, the string is split at each white space resulting in a list of words.
Step 3: Using split() with a specified separator
You can also specify a separator or delimiter other than whitespace. For example, let’s split a string using a comma as a separator:
1 2 3 |
csv_data = "apple,orange,banana,grape" fruits = csv_data.split(',') print(fruits) |
The output will be:
['apple', 'orange', 'banana', 'grape']
In this case, the string is split at each comma, resulting in a list containing the separated values.
Step 4: Using split() with a specified maxsplit value
Using the maxsplit
parameter, you can limit the number of splits that the split() function performs. For example:
1 2 3 |
text = "Learn to use the split function in Python" words = text.split(" ", 2) print(words) |
The output will be:
['Learn', 'to', 'use the split function in Python']
Here, we set maxsplit to 2 and used space as a separator, so the function performs only two splits, resulting in a list containing three substrings.
Full Code
1 2 3 4 5 6 7 8 9 10 11 |
text1 = "Learn to use the split function in Python" words1 = text1.split() print(words1) csv_data = "apple,orange,banana,grape" fruits = csv_data.split(',') print(fruits) text2 = "Learn to use the split function in Python" words2 = text2.split(" ", 2) print(words2) |
Conclusion
In this tutorial, we learned how to use the split() function in Python to break a string into a list of substrings based on a specified delimiter or separator. It is a very powerful and useful function for text processing and analyzing data stored in the form of strings.