简体   繁体   中英

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() .

Splitting on \\n and \\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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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