Home >Backend Development >Python Tutorial >How Can I Split a String Using Multiple Delimiters in Python?

How Can I Split a String Using Multiple Delimiters in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 01:07:091028browse

How Can I Split a String Using Multiple Delimiters in Python?

Splitting Strings with Multiple Delimiters in Python

Splitting strings with multiple delimiters can be a tricky task, especially without using regular expressions. However, Python offers a built-in solution using the re.split() function.

To split a string on either ';' or ', ' (a comma followed by a space), we can use the following pattern:

re.split('; |, ', string_to_split)

This pattern matches any occurrence of ';' or ', ' and splits the string accordingly. For example, the following string:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"

will be split into:

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') 

Update:

As noted in the comment, we can extend the pattern to split on multiple delimiters, including * and line breaks (n):

re.split('; |, |\*|\n', string_to_split)

This will split the following string:

'Beautiful, is; better*than\nugly'

into:

['Beautiful', 'is', 'better', 'than', 'ugly']

The above is the detailed content of How Can I Split a String Using Multiple Delimiters in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn