有很多选项,如此处所示。一个不错的方法是列表推导。
让我们考虑两个字符串,一个满足条件,另一个不满足:
>>> 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。
由于我们希望所有个字符都匹配,我们可以使用all() function。它需要一个值列表;如果其中至少有一个为假,则返回假:
>>> 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):
应该有一种——最好只有一种——明显的方式来做到这一点。
不过没关系,现在你可以选择任何你喜欢的:)