>>test_str.split(',')['helloworld','nicetomeetyou']>> >test_str.split('')[&"/> >>test_str.split(',')['helloworld','nicetomeetyou']>> >test_str.split('')[&">

Home >Backend Development >Python Tutorial >How to split a Python string into a list using multiple delimiters

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

PHPz
PHPzforward
2023-05-04 13:10:061759browse

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

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

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

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete