这里有很多选择。一个好的方法是列出理解。
让我们考虑两个字符串,一个满足条件,另一个不满足条件:>>> 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
生成器表达式>>> 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.
但没关系,现在你可以选择你喜欢的任何东西:)