简体   繁体   English

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

[英]python split string that by space and new line character

I have this code: 我有这个代码:

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

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

My question is: can I do a split with multiple delimiters rather than replace first, then do a split? 我的问题是:我可以使用多个分隔符进行拆分而不是先替换,然后进行拆分吗?

Use re.split() . 使用re.split()

Splitting on \\n and \\t : 拆分\\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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM