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
Release: 2024-12-31 14:18:12
Original
347 people have browsed it

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

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

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

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

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