【问题标题】:How to I check that a string contains only digits and / in python?如何在python中检查字符串是否只包含数字和/?
【发布时间】:2016-05-09 23:03:27
【问题描述】:

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

if Variable.isdigit() == False:

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

【问题讨论】:

  • 使用for循环逐个字符检查
  • 感谢大家的帮助,这对解决问题非常有用!

标签: python string if-statement


【解决方案1】:

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

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

>>> 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):

应该有一种——最好只有一种——明显的方式来做到这一点。

不过没关系,现在你可以选择任何你喜欢的:)

【讨论】:

    【解决方案2】:

    您可以使用以下正则表达式。

    import re
    
    matched = re.match(r'^-?[0-9/]+$', '01/02/2016')
    if matched:
        print 'Matched integers with slashes'
    

    【讨论】:

      【解决方案3】:

      使用正则表达式:

      import re
      if re.match("[0-9/]+$", variable):
          pass # do something
      

      re.match 从头开始​​检查变量是否与表达式匹配。该表达式由字符类[0-9/](数字和斜杠)、+(表示一次或多次)和一个代表行尾的美元符号组成,因此它确保字符串不仅开始带有数字(或斜线),但也一直匹配字符类直到结束。

      【讨论】:

        【解决方案4】:

        您可以使用for 循环来逐字符检查

        def check(text):
        
           for char in text:
               if not (char.isdigit() or char == '/'):
                   return false
        
           return true
        
        if check(you_text):
            print("OK")
        

        如果您需要不同的字符,您可以使用带有允许字符的列表或文本 - 类似于:

        def check(text):
        
           for char in text:
               if char not in "0123456789/":
                   return false
        
           return true
        

        【讨论】:

        • 您可以将"0123456789/" 测试字符串转换为frozenset 以加快测试速度...但我怀疑这里的正则表达式可能更快,因为Python 循环的速度相对较慢。
        【解决方案5】:

        只是另一个想法。

        >>> set('01/02/2016') <= set('0123456789/')
        True
        >>> set('01/02 2016') <= set('0123456789/')
        False
        

        【讨论】:

          【解决方案6】:

          您也可以使用列表推导和any() 函数来做到这一点:

          In [1]: mystring = '01/02/2016'
          
          In [2]: all(c in '0123456789/' for c in mystring)
          Out[2]: True
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-11-22
            • 1970-01-01
            • 2012-08-20
            • 2014-02-18
            • 2017-07-04
            • 2011-07-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多