I want to get numeric data from string. How to do that in python???
For e.g. From string "data23/45 data" extract 23 and 45
I'm sure there are hundreds of ways, but one way is to use a regular expression to split the string into digit groups, and a list comprehension to convert the values to integers;
>>> import re
>>> a = "data23/45 data"
>>> [int(x) for x in re.split('[^\d]+', a) if x]
[23, 45]
re.split('[^\d]+', a)
will split on non digits, which leaves only the digit groups in the result. The outer list comprehension will convert all non empty values in the result to integers.
Of course, if you want the digit groups still as strings, you can use the simpler;
>>> [x for x in re.split('[^\d]+', a) if x]
['23', '45']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句