split 和strip方法

在python3:

split

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

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in 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.

即:返回一个用sep作为分隔符的列表给S。如果maxsplit已经指定,起码最多分成几块已经定了。如果sep没有被指定或者为None,那么所有的空格都是分隔符,空串也会被从结果中删除。

strip

>>> help(line_spoken.strip)
Help on built-in function strip:

strip(...) method of builtins.str instance
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

即返回一个字符串S去掉开头和结尾空格的副本。如果chars是指定非空的,则删除这个chars指定的字符。

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值