简体   繁体   中英

Split a string with python re

I'm reading a file from std input a line at the time with python and every line is in the following format:

Id:0\t1.0,0.0,83,212,302,475\n

where \\t stands for tab and \\n for new line. I would like to use python regex to parse it and obtain a list containing all and only the numbers of the string.

E.g. ['0','1.0','0.0','83','212','302','475']

Can you please tell me how to implement this in a one-liner?

my_str = 'Id:0\t1.0,0.0,83,212,302,475\n'

re.findall('[\d\.]+',my_str)
Out[144]: ['0', '1.0', '0.0', '83', '212', '302', '475']

You could alternately do it like this:

[x.strip('Id:\n') for x in re.split('[\t,]',my_str)]
Out[143]: ['0', '1.0', '0.0', '83', '212', '302', '475']

But that's a little fragile (and harder to read)

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