python拆分字符串,按空格和换行符

时间:2016-08-14 04:06:01

标签: python split

我有这段代码:

f1=open('test.txt','r')
d={}
line = f1.read().replace('\n',' ')
line2= line.split("\n")

line = "This is line1\nthis isline2\nthis is line3"

我的问题是:我可以使用多个分隔符进行拆分而不是替换 首先,然后做分裂?

1 个答案:

答案 0 :(得分:4)

使用re.split()

分割到\n\t

In [23]: line = "This is line1\nthis isline2\tthis is line3"

In [24]: re.split(r'[\n\t]', line)
Out[24]: ['This is line1', 'this isline2', 'this is line3']
相关问题