如何取出一组字符串中的数字(整数或小数)
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.
本文介绍如何使用Python的正则表达式模块re从包含数字的字符串中提取整数和浮点数。通过使用特定的正则表达式模式,可以匹配并分离出字符串内的所有数字,包括整数和小数。
&spm=1001.2101.3001.5002&articleId=107091418&d=1&t=3&u=c0e49263f55140a18f860acfd3bd98e1)

被折叠的 条评论
为什么被折叠?



