Skip to content

Python split multiple delimiters | Example code

  • by

Use the built-in split method to split strings with multiple delimiters in Python. Just pass multiple delimiters with space into a method.

import re
re.split('; |, ',str)

Example Split string with multiple delimiters in Python

Simple example code. Where delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character.

You have to import the re module for this example.

import re

s = 'Beautiful, is; better*than\nugly'

res = re.split('; |, |\*|\n', s)

print(res)

Output:

Python split multiple delimiters

Another example

import re
text = 'The quick brown\nfox jumps*over the lazy dog.'
print(re.split('; |, |\*|\n',text))

Output: [‘The quick brown’, ‘fox jumps’, ‘over the lazy dog.’]

Here is an one more example code snippet:

import re

string = "apple,banana;cherry grape orange"

# Split the string using commas, semicolons, and spaces as delimiters
result = re.split(r'[,;\s]+', string)

print(result)  # Output: ['apple', 'banana', 'cherry', 'grape', 'orange']

In the above example, the re.split() function splits the string string using the regular expression pattern [,;\s]+, which matches one or more occurrences of commas, semicolons, or whitespace characters.

Do comment if you have any doubts or suggestions on this Python split topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading