有很多选项,如此处所示。列表推导式是一个不错的选择。
让我们考虑两个字符串,一个满足条件,另一个不满足:
>>> match = "123/456/"
>>> no_match = "123a456/"
我们可以使用以下方法检查其中的字符是否匹配isdigit()
和比较:
>>> match[0].isdigit() or match[0] == '/'
True
但我们想知道是否所有字符都匹配。我们可以通过使用获得结果列表列表推导式 https://docs.python.org/2/tutorial/datastructures.html#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]
请注意,不匹配字符串的列表有False
在同一位置'a'
char.
既然我们想要all要匹配的字符,我们可以使用all()功能 https://stackoverflow.com/questions/19389490/how-pythons-any-and-all-functions-work。它需要一个值列表;如果其中至少一个为 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
生成器表达式
生成器表达式 https://docs.python.org/2/reference/expressions.html#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)
请注意,这只是选项之一。可悲的是,你的问题失败了Python之禅推荐 https://www.python.org/dev/peps/pep-0020/ (>>> import this
):
应该有一种(最好只有一种)明显的方法来做到这一点。
但没关系,现在你可以选择你喜欢的任何东西:)