这篇文章主要介绍了举例详解Python中的split()函数的使用方法,split()函数的使用是Python学习当中的基础知识,通常用于将字符串切片并转换为列表,需要的朋友可以参考下
函数:split()
Python中有split()和os.path.split()两个函数,具体作用如下:
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(list)
os.path.split():按照路径将文件名和路径分割开
一、函数说明
1、split()函数
语法:str.split(str="",num=string.count(str))[n]
参数说明:
str: 表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]: 表示选取第n个分片
注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略
2、os.path.split()函数
语法:os.path.split('PATH')
参数说明:
PATH指一个文件的全路径作为参数:
如果给出的是一个目录和文件名,则输出路径和文件名
如果给出的是一个目录名,则输出路径和为空文件名
二、实例
1、常用实例

2、去掉换行符

3、分离文件名和路径

4、一个超级好的例子

网友评论