python判断是否包含某数字_如何检查字符串是否只包含数字和/在python中?

本文讲解了如何使用Python检查字符串中的每个字符,确保它们仅包含数字或斜杠,并通过函数`digit_or_slash`实现。通过实例演示了isdigit()函数、列表推导和all()函数的应用,以及如何选择合适的语法进行字符串匹配。
摘要由CSDN通过智能技术生成

这里有很多选择。一个好的方法是列出理解。

让我们考虑两个字符串,一个满足条件,另一个不满足条件:>>> 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.

但没关系,现在你可以选择你喜欢的任何东西:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值