我正在尝试从所有文本中剥离一个字符串并将其转换为整数,以便我可以更轻松地在其上使用 if 语句......
例:
count = "19 Count"
count = count.replace(" Count", "")
print repr(count)
print int(count)
示例输出:
'19'
19
但是在我的实际代码中,我的输出是:
实际输出:
u'19'
Traceback (most recent call last):
File "C:test.py", line 153, in <module>
print int(count)
ValueError: invalid literal for int() with base 10: ''
错误ValueError: invalid literal for int() with base 10: ''
的原因是您在int()
中传递空字符串。喜欢int('')
.主要问题在于去除非数字字符的代码。
正则表达式可用于获取第一个数字。
In [3]: import re
In [4]: a = re.search('d+', ' 18 count 9 count')
In [5]: int(a.group())
Out[5]: 18
检查每个单词的数字,并使用过滤器输出如果它是真的。
>>> count = "19 Count"
>>> filter(lambda x:x.isdigit(), count)
'19'
试试这个,以满足你的要求。 将仅匹配第一组"数字":
import re
regex = re.compile("(d+)")
r = regex.search("19 Count 1 Count")
print(int(r.group(1)))
输出:
19
您可以在此处试用代码:http://ideone.com/OwbMYm