我有一份清单。我想检查它是否包含数字
list1 = [u'Studied at ', u'South City College, Kolkata', u'Class of 2012',
u'Lives in ', u'Calcutta, India', u'From ', u'Calcutta, India']
>>> if re.match(r'[\w-]+$', str(list1)):
print "contains a number"
else:
print "does not contain number"
它不包含任何数字。 需要一些帮助。我希望输出为“2012”
答案 0 :(得分:4)
为模式re.search
做一个\d
。不要re.match
,只匹配字符串的开头。
答案 1 :(得分:3)
\d
正则表达式怎么样?
>>> import re
>>> l = [u'Studied at ', u'South City College, Kolkata', u'Class of 2012', u'Lives in ', u'Calcutta, India', u'From ', u'Calcutta, India']
>>> digit_re = re.compile('\d')
>>> [item for item in l if digit_re.search(item)]
[u'Class of 2012']
或者,如果你想提取数字:
>>> for item in l:
... match = digit_re.search(item)
... if match:
... print "%s: %s" % (item, match.group(1))
...
Class of 2012: 2012