方法:split() python3

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

参数说明:
1.PATH指一个文件的全路径作为参数:
2.如果给出的是一个目录和文件名,则输出路径和文件名
3.如果给出的是一个目录名,则输出路径和为空文件名
eg.

import os
man=[ ]
other=[ ]
try:
        data=open('sketch.txt')
        for each_line in data:
                try:
                        (role,line_spoken)=each_line.split(':',1) #把剧本的分割一次,每行遇到第一个:分割一次,然后到下一行继续 
      #                        print(role,end='')
                        line_spoken=line_spoken.strip()
                        if role == 'Man':
                                man.append(line_spoken)
                        elif role == 'Other Man':
                                other.append(line_spoken)
                        #print(' said: ',end='')
                        #print(line_spoken,end='')
                except ValueError:
                        pass
        data.close()
except IOError:
        print('The datafile is missing!')

try:
        man_file=open('man_data.txt','w')
        other_file=open('other_data.txt','w')

        print(man)
        print(other)

#        print(man,file=man_file)#将man保存到man_file
#        print(other,file=other_file)

except IOError:
        print('File error.')

finally:
        man_file.close()
        other_file.close()

#print(man)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值