4-1如何拆分含有多个分隔符的字符串

本文介绍了使用Python进行字符串拆分的多种方法,包括str.split()的基础用法、结合map()和lambda实现复杂拆分,以及利用正则表达式re.split()进行高级分割。通过实例演示了如何针对不同分隔符灵活运用这些技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、介绍str.split()用法

上一篇《python调用shell命令》介绍了如何用python调用系统命令。

(1)列出windows进程列表 

>>> import os
>>> tmp = os.popen('tasklist').readlines()
>>> tmp

(2)取出切片,显示最后一行

>>> s = tmp[-1]
>>> s

'tasklist.exe                  6524 Console                    1      5,740 K\n'

(3)将字符串拆分

Str.split()用法

>>> help(s.split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
from the result.
help(s.split)

如果以空白分隔符(\t、\r、\n空格等)为拆分时分隔符参数可以不传或传入None。

 

>>> s.split()

['tasklist.exe', '6524', 'Console', '1', '5,740', 'K']

2、采用多次str.split()方法

>>> s = 'ab;cd|df,oi.kjqw;soic\sf'
>>> def mysplit(s,ds):
    res = [s]            #将字符串s转为列表,列表包含一个大的字符串
    for d in ds:
        t = []
        map(lambda x : t.extend(x.split(d)) , res) #将每次从res分割的字符串添加到列表t中
        res = t   #再把列表t赋值给res,做为下次迭代时使用,新的分割后的列表
    return [x for x in res if x]  #将字符串过滤,防止有两个相近的分割符导致,出出None空字符串。

>>> mysplit(s,";|,.\\")

['ab', 'cd', 'df', 'oi', 'kjqw', 'soic', 'sf']

Map()函数在《2-5查找字典公共键》中有过介绍,map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。此例中,lambda的参数x即为res列表的每一个元素(只有一个元素是一个大列表)。

 

列表的extend在《2-1 如何在列表字典集合中根据条件筛选数据》中有过举例,这个函数是将添加的函数不管是什么,都转为一元列表。Lambda用法也在这里有过介绍。

 

mysplit()函数推导过程

>>> s
'ab;cd|df,oi.kjqw;soic\\sf'
>>> s1 = s.split(';')
>>> s1

['ab', 'cd|df,oi.kjqw', 'soic\\sf']

s.split()分割后的字符串组成了列表,s1是列表没有split()函数,此时要对s1列表中各个元素再进行分割,可以用map()函数,因为他是将某个功能作用在可迭代对象的各个元素上的,正好,每个元素实际上是一个字符串。

>>> new = map(lambda x : x.split('|'),s1)
>>> new

[['ab'], ['cd', 'df,oi.kjqw'], ['soic\\sf']]

执行两次后,new变成了一个二维列表,列表中还有列表,所以用到了,空列表,进行extend()转化为一维列表的思想。

3、使用re.split()方法

>>> import re
>>> re.split(r'[;|,.\\]+',s)

['ab', 'cd', 'df', 'oi', 'kjqw', 'soic', 'sf']

>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.
help(re.split)

正则表达式在《2-3统计序列元素出现的频度》中有过介绍,re.split()函数的第一个参数为“正则表达式的规则”,本例中,[;|,.\\]为方括号中的元素中的任意一个。后面的+号表式有1或无限多个。

 

转载于:https://www.cnblogs.com/smulngy/p/8861639.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值