How to Split Strings in Python Using Multiple Characters?

Estimated read time 1 min read

In Python, you can split a string using multiple characters as delimiters using the split() method of strings with the re module. Here’s an example:

import re

my_string = "Hello, world; how are you today?"
delimiter_pattern = r", |; "

split_strings = re.split(delimiter_pattern, my_string)

print(split_strings)

In this example, we first import the re module, which provides regular expression functionality in Python.

We then define the string we want to split, my_string, and the delimiter pattern we want to use to split the string. In this case, we use the regular expression pattern ", |; ", which matches either a comma followed by a space or a semicolon followed by a space.

Finally, we use the re.split() method to split the string using the delimiter pattern, and assign the result to split_strings. We then print split_strings, which will contain a list of the substrings obtained by splitting my_string using the delimiter pattern.

The output of this example code would be:

['Hello', 'world', 'how are you today?']

Note that the spaces around the delimiter characters are not included in the resulting substrings.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply