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

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

DDD
Release: 2024-12-30 10:18:10
Original
894 people have browsed it

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

Splitting Strings with Multiple Delimiters in Python

The task of splitting a string using multiple delimiters can be encountered in various programming scenarios. Without utilizing regular expressions, this operation can be perceived as challenging. However, Python offers a straightforward solution for this problem.

For cases where a string needs to be split by either a semicolon or a comma followed by a space, regular expressions are not necessary. Python provides a remarkable solution for this specific scenario.

Consider the following Python code:

import re

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

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

print(result)
Copy after login

The output of this code will be a list of strings as follows:

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

As we can observe, the string was successfully split based on the provided delimiters. This allows you to work with individual parts of the string conveniently and effectively. Note that commas without trailing spaces remain untouched, as specified in the requirements.

The above is the detailed content of How Can I Split a String Using Multiple Delimiters in Python Without Regular Expressions?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template