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)

你可能感兴趣的:(Python)