Split String With Multiple Delimiters In Python

Split String with multiple delimiters

In this post, we will see how to split String with multiple delimiters in Python.

Splitting a string in Python

When we talk about splitting a string, it means creating a collection of sub-strings out of a string. We can split a string by a character and create a list of sub-strings. In Python, we can split a string by single or multiple delimiter characters.

Ways to split a string in Python

We will now discuss how to split a string based on multiple delimiters in python.

Using the split() and replace() functions

We can use the split() function to split a string based on some delimiter in Python. First, we will replace the second delimiter with the first delimiter using the replace() function.

Then, we proceed to split the string using the first delimiter using the split() function that will return a list of sub-strings.

See the code below.

Output:

[‘split’, ‘ the’, ‘ string’, ‘ multiple’, ‘ delimiters’]

In the above example,

  • We replace the ; character with , using the replace() function.
  • Then we split the string based on the , character using the string() function.

Using the regular expressions

Regular expressions are clean, compact patterns that can match parts of the strings. To use regular expressions in Python, we use the re library.

We use the re.split() to split the string based on the occurrence of some pattern. To split a string using multiple delimiters, we specify multiple delimiters in the pattern.

For example,

Output:

[‘split’, ‘ the’, ‘ string’, ‘ multiple’, ‘ delimiters’]

We can also use this function in another way. First, we will create a pattern using the re.compile() function and then use it separately with the re.split() function.

For example,

Output:

[‘split’, ‘ the’, ‘ string’, ‘ multiple’, ‘ delimiters’]

This method is a good way to use regular expressions as it allows reusability of the pattern.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *