How To Use Split In Python

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:

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:

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:

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:

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

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.