如何从带有减号的字符串中提取数字

时间:2014-09-04 22:26:40

标签: python

我需要能够从字符串中提取两个数字。我知道这两个数字(如果用字符串表示)是用' - '字符。

a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'

显然我需要以简单但可靠的方式提取零0376。因此,无论字符串中的数字位于何处,代码都可以工作:在开头,中间或结尾。它应该是一个恒定的结果,无论数字周围是什么字符:字母,逗号,句号,美元或英镑符号等。

2 个答案:

答案 0 :(得分:2)

这听起来像是正则表达式的工作:

import re

a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'


for text in a, b, c, d:
    match = re.search(r'(\d+)-(\d+)', text)
    if match:
      left, right = map(int, match.groups())
      print left, right

答案 1 :(得分:1)

您可以使用正则表达式实现所需:

import re
regex = re.compile('([0-9]+)-([0-9]+)')
match = regex.search('some text.0-376.some text again')
if match:
    numbers = [int(s) for s in match.groups()]
    # numbers -> [0, 376]