Table of Contents
Use square brackets [] to split a string based on multiple delimiters
Handling leading or trailing delimiters
Use str.replace() to split a string with multiple delimiters
Use reusable function to split string based on multiple delimiters
Use re.findall() to split a string into a list of words
Home Backend Development Python Tutorial In Python, how to split a string containing multiple delimiters?

In Python, how to split a string containing multiple delimiters?

May 09, 2023 pm 07:25 PM
python

To split a string using multiple delimiters:

Use the re.split() method, for example re.split(r',|-', my_str).

re.split() method will split all occurrences of a string with one of the delimiters.

import re
# ????️ 用 2 个分隔符拆分字符串
my_str = 'fql,jiyik-dot,com'
my_list = re.split(r',|-', my_str)  # ????️ 以逗号或连字符分隔
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

re.split method accepts a pattern and a string and splits the string each time the pattern occurs.

Pipe | character is an or. Matches A or B.

This example splits the string using 2 delimiters (comma and hyphen).

# ????️ 用 3 个分隔符拆分字符串
my_str = 'fql,jiyik-dot:com'
my_list = re.split(r',|-|:', my_str)  # ????️ comma, hyphen or colon
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

Here is an example of splitting a string using 3 delimiters (comma, hyphen and colon).

We can use as many | characters as necessary in the regular expression.

Use square brackets [] to split a string based on multiple delimiters

Alternatively, we can use square brackets [] to indicate a group of characters.

import re
my_str = 'fql,jiyik-dot,com'
my_list = re.split(r'[,-]', my_str)
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

In Python, how to split a string containing multiple delimiters?

Make sure to add all delimiters between square brackets.

import re
# ????️ 用 3 个分隔符拆分字符串
my_str = 'fql,jiyik-dot:com'
my_list = re.split(r'[,-:]', my_str) # 以逗号、连字符、冒号分割
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

If the string starts or ends with one of these delimiters, we may get empty string values ​​in the output list.

Handling leading or trailing delimiters

We can use list comprehension to remove any empty string from the list.

import re

# ????️ 用 3 个分隔符拆分字符串
my_str = ',fql,jiyik-dot:com:'

my_list = [
    item for item in re.split(r'[,-:]', my_str)
    if item
]

print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

List comprehension is responsible for removing empty strings from the list.

List comprehensions are used to perform certain operations on each element or to select a subset of elements that satisfy a condition.

Another way is to use the str.replace() method.

Use str.replace() to split a string with multiple delimiters

To split a string with multiple delimiters:

  • Use the str.replace() method to replace the first delimiter with the second delimiter.

  • Split the string by the second delimiter using the str.split() method.

my_str = 'fql_jiyik!dot_com'
my_list = my_str.replace('_', '!').split('!')
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com']
Copy after login

This method is only convenient when there are few delimiters you want to split, such as 2.

First, we Replace every occurrence of the first delimiter with the second delimiter, and then we split the second delimiter.

str.replace method returns a copy of the string in which all occurrences of the substring are replaced by the provided replacement.

This method takes the following parameters:

  • #old The substring we want to replace in the string

  • new Replace every occurrence of old

  • count Replace only the first occurrence of count (optional)

Please note that this method does not change the original string. Strings are immutable in Python.

Here is another example.

my_str = 'fql jiyik, dot # com. abc'

my_list = my_str.replace(
    ',', '').replace(
    '#', '').replace('.', '').split()

print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com', 'abc']
Copy after login

We use the str.replace() method to remove punctuation before splitting the string on whitespace characters.

We use an empty string for replacement because we want to delete the specified characters.

We can chain as many calls to the str.replace() method as needed.

The final step is to split the string into a list of words using the str.split() method.

str.split() method splits a string into a list of substrings using delimiters.

This method takes the following 2 parameters:

  • #separator Split the string into substrings every time a separator appears

  • maxsplit Complete maxsplit splitting at most (optional)

When no delimiter is passed to str. split() method, it splits the input string into one or more whitespace characters.

my_str = 'fql jiyik com'
print(my_str.split())  # ????️ ['fql', 'jiyik', 'com']
Copy after login

If the delimiter is not found in the string, then a list containing only 1 element is returned.

Use reusable function to split string based on multiple delimiters

If we need to split string based on multiple delimiters frequently, please define a reusable function.

import re

def split_multiple(string, delimiters):
    pattern = '|'.join(map(re.escape, delimiters))

    return re.split(pattern, string)

my_str = 'fql,jiyik-dot:com'

print(split_multiple(my_str, [',', '-', ':']))
Copy after login

split_multiple The function accepts a string and a list of delimiters and splits the string based on the delimiter.

str.join() method is used to join the delimiter with the pipe |. Divider.

# ????️ ,|-|:
print('|'.join([',', '-', ':']))
Copy after login

This will create a regular expression pattern that we can use to split a string based on the specified delimiter.

If we need to split a string into a word list with multiple delimiters, we can also use the re.findall() method.

Use re.findall() to split a string into a list of words

Use the re.findall() method to split a string into a list of words with multiple delimiters word list.

re.findall() The method will split the string every time a word occurs and return a list containing the word.

import re

# ✅ 将字符串拆分为具有多个分隔符的单词列表
my_str = 'fql jiyik, dot # com. abc'

my_list = re.findall(r'[\w]+', my_str)
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com', 'abc']
Copy after login

re.findall The method takes a pattern and a string as parameters and returns a list of strings containing all non-overlapping occurrences of the pattern in the string.

我们传递给 re.findall() 方法的第一个参数是一个正则表达式。

import re

my_str = 'fql jiyik, dot # com. abc'

my_list = re.findall(r'[\w]+', my_str)
print(my_list)  # ????️ ['fql', 'jiyik', 'dot', 'com', 'abc']
Copy after login

方括号 [] 用于表示一组字符。

\w 字符与 Unicode 单词字符匹配,并且包括可以作为任何语言的单词一部分的大多数字符。

加号 + 使正则表达式匹配前面字符(Unicode 字符)的 1 次或多次重复。

re.findall() 方法返回一个包含字符串中单词的列表。

The above is the detailed content of In Python, how to split a string containing multiple delimiters?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles