Python分割包含空格和换行符的字符串

4

I have this code:

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

line = "这是第1行\n这是第2行\n这是第3行"

我的问题是:我是否可以使用多个分隔符来分割字符串,而不需要先进行替换,然后再进行分割?

1个回答

5
使用 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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接