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

How Can I Split a Python String Using Multiple Delimiters?

Susan Sarandon
Susan SarandonOriginal
2024-12-31 14:18:12335browse

How Can I Split a Python String Using Multiple Delimiters?

Splitting Strings with Multiple Delimiters in Python

You need to split a string into multiple segments using either a semicolon (;) or a comma followed by a space (', '). Regular expressions can be useful for solving this problem.

Pythonic Solution

Thankfully, Python offers a built-in solution:

import re

delimiters = '; |, '
split_string = re.split(delimiters, string_to_split)

re.split() splits the string based on the pattern provided in the delimiters variable. This pattern includes both the semicolon and comma with trailing space.

Example:

Consider the 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]"

Splitting this string using the Pythonic solution yields:

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

Handling Multiple Delimiters

You can split on multiple delimiters by providing a pipe (|) between them in the regular expression pattern. For instance, to split on a comma or asterisk (*), modify the delimiters variable as follows:

delimiters = '; |, |*|\n'

This would then 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 Python String Using Multiple Delimiters?. 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