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
Release: 2024-12-11 01:07:09
Original
1010 people have browsed it

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)
Copy after login

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]"
Copy after login

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]') 
Copy after login

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)
Copy after login

This will split the following string:

'Beautiful, is; better*than\nugly'
Copy after login

into:

['Beautiful', 'is', 'better', 'than', 'ugly']
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template