简体   繁体   中英

Separate digits from text in Python

I'm trying to separate numbers from a string in Python such as this example:

text = "Compute the average of 5,7". (I want to get a list [5,7])

(the comma between the numbers is a must) I've tried using:

numbers = [int(i) for i in text.split() if i.isdigit()]

It works when the numbers aren't separated by the comma but when written with a comma I just receive an empty list.

Use a regular expression to find two integers separated by comma.

import re

m = re.search(r'(\d+),(\d+)', text)
if m:
    numbers = [int(x) for x in m.groups()]

Try this:

text = "Compute the average of 5,7"
nums = [int(i) for i in text if i.isdigit()]
print(nums)
# prints [5, 7]
>>> import re
>>> re.search('.*(\d,\d).*', text).group(1)
'5,7'

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