gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:22:07 24 4
gpt4 key购买 nike

我正在尝试检查字符串是否仅包含/和数字,以用作验证形式,但是我找不到同时执行这两项操作的方法。 ATM 我有这个:

if Variable.isdigit() == False:

这适用于数字,但我还没有找到一种方法来检查斜杠。

最佳答案

有很多选项,如此处所示。列表推导式是一个不错的选择。

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

>>> 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 。它需要一个值列表;如果至少其中一个为 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.

但是没关系,现在你可以选择你喜欢的任何内容:)

关于python - 如何检查字符串是否只包含数字和/在Python中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com