Home > Backend Development > Python Tutorial > How Can I Split Strings with Multiple Delimiters in Python?

How Can I Split Strings with Multiple Delimiters in Python?

Patricia Arquette
Release: 2024-12-14 01:47:12
Original
187 people have browsed it

How Can I Split Strings with Multiple Delimiters in Python?

Splitting Strings with Multiple Delimiters in Python

When dealing with strings that require splitting based on specific delimiters, Python offers a convenient solution without the need for regular expressions.

The Split Function

Python's split function allows you to split a string based on a provided delimiter. By utilizing multiple delimiters separated by the pipe character ('|'), you can achieve splitting on various conditions.

For instance, the following code snippet demonstrates splitting a string on both semicolons (';') and commas followed by a space (', '):

import re

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

split_list = re.split(delimiters, string_to_split)

print(split_list)
Copy after login

This will produce the desired list:

['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

Additional Delimiters

To extend the splitting functionality to include other delimiters, such as the asterisk (*) or newline character (n), simply append them to the delimiters string, separated by the pipe character. For example:

delimiters = '; |, |\*|\n'
Copy after login

With this modification, you can split the following string:

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

Into:

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

By leveraging Python's split function and the flexibility of multiple delimiters, you can efficiently manipulate strings to meet your specific requirements.

The above is the detailed content of How Can I Split Strings with 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