如何取出一组字符串中的数字(整数或小数)
import re
>>> s = '4 and 10.2356'
>>> re.findall(r'\d+(?:\.\d+)?', s)
['4', '10.2356']
>>> print(int(re.findall(r'\d+(?:\.\d+)?', s)[0]))
4
>>> print(float(re.findall(r'\d+(?:\.\d+)?', s)[1]))
10.2356
- \d+: matches one or more digits.
- \d+.\d+ :matches one or more digits plus any single character plus one or more digits.
- \d+.\d+ :matches one or more digit characters pus a literal dot plus one or more digits.
- \d+(?:.\d+)? :matches integer as well as floating point numbers because we made the pattern which matches the decimal part as optional. ? after a capturing or non-capturing group would turn the whole group to an optional one.