【看这个就够了】Python中split()方法深度解析(看完这个你再不会算我输)

1 定义

1.1 描述

Python中split() 方法通过指定分隔符对字符串进行切片并返回一个列表。

1.2 语法格式

string.split(str="", num=string.count(str))

参数说明:
1. str: 分隔符,默认为所有的空字符,
包括 空格、换行(\n)、水平制表符(\t)、 垂直制表符(\v)、 换页(\f)、回车(\r);(python中转义字符表看附)
2. num: 分割次数。默认为 -1, 即分隔所有。

如果参数 num 有指定值,则分隔 num+1 个子字符串

2 实战

2.1 参数为空情况

分隔符str 默认为所有的空字符,包括 空格、换行(\n)、水平制表符(\t)、 垂直制表符(\v)、 换页(\f)、回车(\r)。
(有些同志博客只提到了空格、换行\t、制表\t、实则还包括\v \f \r)

string = 'abcd efg\nopq\trst\vuvw  x\fyz'
print(string)
print('======切分后=========')
stringlist = string.split()
print(stringlist)

# 输出结果
abcd efg
opq	rstuvw  xyz
======切分后=========
['abcd', 'efg', 'opq', 'rst', 'uvw', 'x', 'yz']

2.2 单个分隔符情况

2.2.1 以空格作为分隔符

string = 'hello world,\nhello python.'
print(string)
print('======切分后=========')
print(string.split(" "))

# 输出结果
hello world,
hello python.
======切分后=========
['hello', 'world,\nhello', 'python.']

注意:str分隔符必须为字符
错误示例:

string = 'python2 and python 3.'
print(string.split(2))

# 输出结果
TypeError: must be str or None, not int

正确示例:

string = 'python2 and python 3.'
print(string.split('2'))

# 输出结果
['python', ' and python 3.']

2.2.2 以其他字符作为分隔符

string = 'hello world,\nhello python.'
print(string.split('o'))

# 输出结果
['hell', ' w', 'rld,\nhell', ' pyth', 'n.']

2.2.3 字符串首尾出现分隔符

当字符串收尾存在分隔符的时候,有多少个分隔符就产生多少个空字符。(不传参情况除外)

string = 'ppphello worldppp,hello pp python.pp'
print(string.split('p'))

# 输出结果
['', '', '', 'hello world', '', '', ',hello ', '', ' ', 'ython.', '', '']

2.2.4 字符串中间出现分隔符

注意:如果是单个出现,就和普通的分割一样;
如果是多个出现,则两个分隔符之间会产生一个空字符

string = 'ppphello worldppp,hello pp python.pp'
print(string.split('p'))

# 输出结果
['', '', '', 'hello world', '', '', ',hello ', '', ' ', 'ython.', '', '']

# 所以这里world后的3个p,产生两个空字符,hello 后面2个p会产生一个空字符。
#再后面的一个是空格字符,不是空字符。

2.2.5 指定分割次数

参数num,分割次数。指定num后,则共有 num+1 个子字符串

string = 'hello world,hello python.'
print(string.split('o', 2))

# 输出结果
['hell', ' w', 'rld,hello python.']

2.3 多个分隔符情况

注意:
Python中split()方法只支持单个分隔符;
re模块的split()函数支持多个分隔符对字符串进行分割,其中不同的分隔符用 “|” 隔开。

2.3.1 多个分隔符例子

import re
string = 'hello world,\nhello python.'
stringlist = re.split(r'e|o|\n',string)
print(stringlist)

# 输出结果
['h', 'll', ' w', 'rld,', 'h', 'll', ' pyth', 'n.']

2.3.2 首尾、中间出现分隔符

与python中split()方法一样的处理。
参考
2.2.3 字符串首尾出现分隔符
2.2.4 字符串中间出现分隔符

import re
string = 'rrhelloooworldee'
stringlist = re.split(r'e|o',string)
print(stringlist)
# 输出结果
['rrh', 'll', '', '', 'w', 'rld', '', '']

3 拓展

与strip()函数区别

  • split()函数可以删除中间和头尾内容

  • strip()函数只能删除头和尾内容

4 附录

Python中的常用转义字符
在这里插入图片描述

如文章对您有帮助,感谢您的点赞+关注(^ _ ^)

  • 18
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值