【问题标题】:Making sure no integers in a string?确保字符串中没有整数?
【发布时间】:2013-05-06 13:23:16
【问题描述】:

我有一个简单的问题。我只是想知道如何让我的程序读取“input()”并查看字符串中是否有整数或任何类型的数字,如果有,则打印出一条消息。几乎我只是想知道如何确保没有人为他们的名字输入数字。谢谢!

yn = None
while yn != "y":
    print("What is your name?")
    name = input()
    print("Oh, so your name is {0}? Cool!".format(name))
    print("Now how old are you?")
    age = input()
    print("So your name is {0} and you're {1} years old?".format(name, age))
    print("y/n?")
    yn = input()
    if yn == "y":
        break
    if yn == "n":
        print("Then here, try again!")
print("Cool!")

【问题讨论】:

    标签: python string integer


    【解决方案1】:

    在字符串上使用str.isdigit() method,以及any() function

    if any(c.isdigit() for c in name):
        # there is a digit in the name
    

    .isdigit() 为任何仅由数字组成的字符串返回True。这包括任何标记为数字或数字小数的 Unicode 字符。

    any() 循环遍历您传入的序列,并在找到第一个元素True 时返回True,如果所有元素都是False,则返回False

    演示:

    >>> any(c.isdigit() for c in 'Martijn Pieters')
    False
    >>> any(c.isdigit() for c in 'The answer is 42')
    True
    

    【讨论】:

    • 我不需要将它与 while 语句合并吗?比如“while name != True”等?
    • @Xiam:不,您不必使用while 声明。 any() 函数内的 for .. in .. 语句称为生成器表达式,它独立存在。
    • 好吧,我想添加一个循环,这样该人就无法在不输入有效名称的情况下继续执行程序(我可能应该解释一下)。这包括一个while循环,是吗?
    • @Xiam:当然,那你也可以使用while 声明。 :-)
    【解决方案2】:

    查看字符串中是否有整数或任何类型的数字

    any(c.isdigit() for c in name)
    

    为诸如“123”、“123.45”、“abc123”之类的字符串返回True

    【讨论】:

      【解决方案3】:

      根据字符串,正则表达式实际上可能更快:

      import re
      
      s1 = "This is me"
      s2 = "this is me 2"
      s3 = "3 this is me"
      
      regex = re.compile(r'\d')
      import timeit
      def has_int_any(s):
          return any(x.isdigit() for x in s)
      
      def has_int_regex(s,regex=re.compile(r'\d')):
          return regex.search(s)
      
      print bool(has_int_any(s1)) == bool(has_int_regex(s1))
      print bool(has_int_any(s2)) == bool(has_int_regex(s2))
      print bool(has_int_any(s3)) == bool(has_int_regex(s3))
      
      
      for x in ('s1','s2','s3'):
          print x,"any",timeit.timeit('has_int_any(%s)'%x,'from __main__ import has_int_any,%s'%x)
          print x,"regex",timeit.timeit('has_int_regex(%s)'%x,'from __main__ import has_int_regex,%s'%x)
      

      我的结果是:

      True
      True
      True
      s1 any 1.98735809326
      s1 regex 0.603290081024
      s2 any 2.30554199219
      s2 regex 0.774269104004
      s3 any 0.958808898926
      s3 regex 0.656207084656
      

      (请注意,即使在专门为any 设计的情况下,正则表达式引擎也会胜出)。但是,对于更长的字符串,我愿意打赌any 最终会更快。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-29
        • 1970-01-01
        • 2020-12-04
        • 2021-10-04
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多