How to split a Python string into a list using multiple delimiters

PHPz
Release: 2023-05-04 13:10:06
forward
1744 people have browsed it

Python's strings have a split by default to split the string into a list:

>>> test_str = "hello world,nice to meet you"
>>> test_str.split(',')
['hello world', 'nice to meet you']
>>> test_str.split(' ')
['hello', 'world,nice', 'to', 'meet', 'you']
Copy after login

What should I do if I want the above string to be split into the following list based on commas and spaces at the same time? ?

['hello', 'world', 'nice', 'to', 'meet', 'you']

At this time, the split of re is It can come in handy, it can use the pattern matched by the regular expression as a separator.

>>> import re
>>> test_str = "hello world,nice to meet you"
>>> re.split('[,| ]', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']
>>> re.split('[, ]', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']
>>> re.split(',| ', test_str)
['hello', 'world', 'nice', 'to', 'meet', 'you']
Copy after login

In fact, re.sub and str.replace of strings have the same effect. re.sub can replace multiple parts that meet regular matching at the same time, not just a fixed string.

Supplement: partition series

The partition series methods include partition () and rpartition ().
partition () Split the string according to the specified separator (sep), start indexing from the left side of the string with the separator separator, stop indexing when the index is reached, and return a tuple containing three elements (tuple) , that is (head, sep, tail).

# 遇到第一个分隔符后就停止索引
print(Str.partition('e'))
# 没有遇到分隔符 , 返回原字符串和两个空字符串
print(Str.partition('f'))
 
# 遇 到 第 一 个 分 隔 符 后 就 停 止 索 引
print(Str.rpartition('e'))
# 没 有 遇 到 分 隔 符 , 返 回 两 个 空 字 符 串 和 原 字 符 串
print(Str.rpartition('f'))
Copy after login

The function of rpartition () is similar to partition (), except that it starts splitting from the end of the string.

The difference between split and partition series methods

Method

Return type whether Contains delimiter
split series method list(list) No
partition series method tuple(tuple) is

The above is the detailed content of How to split a Python string into a list using multiple delimiters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!