如何检查字符串是否只包含数字和/在python中?

2024-05-15 17:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查字符串是否只包含/和数字,以用作验证的形式,但是我找不到并无法同时执行这两种操作。自动取款机我有这个:

if Variable.isdigit() == False:

这对数字有效,但我还没有找到检查斜线的方法。


Tags: 方法字符串falseif数字variable形式斜线
3条回答

这里有很多选择。一个好的方法是列出理解。

让我们考虑两个字符串,一个满足条件,另一个不满足条件:

>>> match = "123/456/"
>>> no_match = "123a456/"

我们可以使用isdigit()和比较来检查它们的字符是否匹配:

>>> match[0].isdigit() or match[0] == '/'
True

但我们想知道所有的字符是否匹配。我们可以使用list comprehensions获得结果列表:

>>> [c.isdigit() or c == '/' for c in match]
[True, True, True, True, True, True, True, True]
>>> [c.isdigit() or c == '/' for c in no_match]
[True, True, True, False, True, True, True, True]

注意,不匹配字符串的列表在'a'字符的同一位置有False

因为我们希望所有字符都匹配,所以可以使用^{} function。它需要一个值列表;如果其中至少有一个值为false,则返回false:

>>> all([c.isdigit() or c == '/' for c in match])
True
>>> all([c.isdigit() or c == '/' for c in no_match])
False

加分

设置一个函数

你最好把它放在一个函数上:

>>> def digit_or_slash(s):
...     return all([c.isdigit() or c == '/' for c in s])
... 
>>> digit_or_slash(match)
True
>>> digit_or_slash(no_match)
False

生成器表达式

Generator expressions往往效率更高:

>>> def digit_or_slash(s):
...     return all(c.isdigit() or c == '/' for c in s)
... 

但在你的情况下,这可能是微不足道的。

in呢?

我希望使用in运算符,如下所示:

>>> def digit_or_slash(s):
...     return all(c in "0123456789/" for c in s)

请注意,这只是其中一个选项。很遗憾,您的问题没有通过这个Zen of Python recommendation>>> import this):

There should be one- and preferably only one -obvious way to do it.

但没关系,现在你可以选择你喜欢的任何东西:)

使用正则表达式:

import re
if re.match("[0-9/]+$", variable):
    pass # do something

re.match从一开始就检查变量是否与表达式匹配。表达式由字符类[0-9/](数字和斜杠)、一个+(表示一次或多次)和一个美元符号(表示行尾)组成,因此它确保字符串不仅以数字(或斜杠)开头,而且始终与字符类匹配到行尾。

您可以使用以下regex。

import re

matched = re.match(r'^-?[0-9/]+$', '01/02/2016')
if matched:
    print 'Matched integers with slashes'

相关问题 更多 >