如何在python中检查字符串仅包含数字和/? [英] How to I check that a string contains only digits and / in python?
问题描述
我试图检查一个仅包含/和数字的字符串,以用作一种验证形式,但是我找不到并做到这两种方式.自动取款机我有这个:
I am trying to check that a string contains only / and digits, to use as a form of validation, however I cannot find and way to do both. ATM I have this:
if Variable.isdigit() == False:
这适用于数字,但我还没有找到一种方法来检查斜线.
This works for the digits but I have not found a way to check also for the slashes.
推荐答案
有很多选项,如下所示.列表解析是一个不错的选择.
There are many options, as showed here. A nice one would be list comprehensions.
让我们考虑两个字符串,一个满足条件,另一个不满足:
Let's consider two strings, one that satisfies the criteria, other that doesn't:
>>> match = "123/456/"
>>> no_match = "123a456/"
我们可以使用 isdigit()
和比较来检查它们的字符是否匹配:
We can check if a character of them matches by using isdigit()
and comparation:
>>> match[0].isdigit() or match[0] == '/'
True
但是我们想知道所有字符是否匹配.我们可以使用列表理解:
But we want to know if all chars match. We can get a list of results by using 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
.
Note that the list of the non-matching string has False
at the same position of the 'a'
char.
Since we want all chars to match, we can use the all()
function. It expects a list of values; if at least one of them is false, then it returns false:
>>> all([c.isdigit() or c == '/' for c in match])
True
>>> all([c.isdigit() or c == '/' for c in no_match])
False
奖励积分
放入功能
您最好将其放在函数上:
Bonus points
Put on a function
You would be better to put it on a function:
>>> 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
Generator expressions tend to be more efficient:
>>> def digit_or_slash(s):
... return all(c.isdigit() or c == '/' for c in s)
...
但是在您的情况下,它还是可以忽略不计的.
But in your case it is probably negligible anyway.
我希望使用 in
运算符,如下所示:
I would prefer to use the in
operator, as below:
>>> def digit_or_slash(s):
... return all(c in "0123456789/" for c in s)
请注意,这只是选项之一.遗憾的是,您的问题未能通过 Python推荐的禅宗(>>>导入此
):
Note that this is only one of the options. Sadly, your problem fails this Zen of Python recommendation (>>> import this
):
应该有一种(最好只有一种)明显的方法.
There should be one- and preferably only one -obvious way to do it.
但是没关系,现在您可以选择自己喜欢的任何东西了:)
But that's ok, now you can choose whatever you prefer :)
这篇关于如何在python中检查字符串仅包含数字和/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!