【问题标题】:Check if space is in a string检查空格是否在字符串中
【发布时间】:2011-03-19 02:25:22
【问题描述】:
' ' in word == True

我正在编写一个程序来检查字符串是否是单个单词。为什么这不起作用,有没有更好的方法来检查字符串是否没有空格/是否是单个单词..

【问题讨论】:

  • 你的意思是它不起作用?你有语法错误吗?您完全没有错误吗?
  • 另外,可以在评论中粘贴代码,只要确保格式化即可。
  • 永远不要使用expression == True 来测试真相。只需使用expression

标签: python string


【解决方案1】:

== 优先于 in,因此您实际上是在测试 word == True

>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True

但你根本不需要== Trueif 需要[评估为真或假的东西],' ' in word 将评估为真或假。所以,if ' ' in word: ... 就好了:

>>> ' ' in w
3: True

【讨论】:

  • 各种空格都不匹配:\n,\r,'',...如果需要匹配,最好用re模块,匹配方法在\ s。它会做一个更好的分词器。
  • 编程宠儿:... == True... != False,或其任何变体。
  • Jukka Suomela 的解释比我的解释要正确一点。根据我的解释,您将测试 word==True 然后 ' ' in True,这没有意义。
【解决方案2】:

if " " in word: 而不是if " " in word == True:

解释:

  • 在 Python 中,例如 a < b < c 等价于 (a < b) and (b < c)
  • 这同样适用于任何比较运算符链,包括 in!
  • 因此' ' in w == True 等同于(' ' in w) and (w == True),这不是你想要的。

【讨论】:

  • 哇。我知道<== 按照您描述的方式工作,但我没有意识到in 也这样做了。我曾假设将它们组合起来会被视为a in (b == c)(a in b) == c。要查看它是否真的如 Jukka 所说的那样解释,您可以尝试'a' in 'abc' == 'abc'。它是True,但如果它以我建议的其他任何一种方式解释,它将是False
【解决方案3】:

有很多方法可以做到这一点:

t = s.split(" ")
if len(t) > 1:
  print "several tokens"

为了确保它匹配每一种空间,你可以使用 re 模块:

import re
if re.search(r"\s", your_string):
  print "several words"

【讨论】:

【解决方案4】:

你可以试试这个,如果它找到任何空格,它会返回第一个空格所在的位置。

if mystring.find(' ') != -1:
    print True
else:
    print False

【讨论】:

  • mystring.find(' ') != -1 布尔值。
  • 即,这可以缩短为print mystring.find(' ') != -1
【解决方案5】:

您可以说 word.strip(" ") 来删除字符串中的任何前导/尾随空格 - 您应该在 if 语句之前执行此操作。这样,如果有人输入诸如 " test " 之类的输入,您的程序仍然可以运行。

也就是说,if " " in word: 将确定字符串是否包含任何空格。如果这不起作用,您能否提供更多信息?

【讨论】:

    【解决方案6】:

    您可以在 Python 3 中使用“re”模块。
    如果确实如此,请使用:

    re.search('\s', word)
    

    如果有匹配,这应该返回“真”,如果没有,则返回“假”。

    【讨论】:

    • 这是不等价的(也匹配普通空格旁边的\t\n\r\f\v)并引入了很多的开销。快速检查显示48.5ns 对应" " in word873ns 对应re.search("\s", word),速度慢了一个数量级以上。正则表达式只能用于真正更复杂的任务。
    【解决方案7】:
    word = ' '
    while True:
        if ' ' in word:
            word = raw_input("Please enter a single word: ")
        else:
            print "Thanks"
            break
    

    这是更惯用的 python - 不需要与 True 或 False 进行比较 - 只需使用表达式 ' ' in word 返回的值。

    此外,您不需要为这么小的 sn-p 代码使用 pastebin - 只需将代码复制到您的帖子中,然后使用小 1 和 0 按钮使您的代码看起来像代码。

    【讨论】:

      【解决方案8】:

      使用这个:

      word = raw_input("Please enter a single word : ")
      while True:
          if " " in word:
              word = raw_input("Please enter a single word : ")
          else:
              print "Thanks"
              break
      

      【讨论】:

        【解决方案9】:
        # The following would be a very simple solution.
        
        print("")
        string = input("Enter your string :")
        noofspacesinstring = 0
        for counter in string:
            if counter == " ":
               noofspacesinstring += 1
        if noofspacesinstring == 0:
           message = "Your string is a single word" 
        else:
           message = "Your string is not a single word"
        print("")   
        print(message)   
        print("")
        

        【讨论】:

          【解决方案10】:
          def word_in(s):
             return " " not in s 
          

          【讨论】:

          • 也许可以考虑告诉问题的作者为什么他的解决方案不起作用以及为什么你认为你的解决方案更好。
          【解决方案11】:

          可以查看下面代码的输出是否为0。

          'import re
          x='  beer   '
          len(re.findall('\s', x))
          

          【讨论】:

            【解决方案12】:

            您通常提到了空格,而不仅仅是空格。我偶然发现了isidentifier 的解决方案。每个 W3 学校:

            如果字符串仅包含字母数字字母 (a-z) 和 (0-9) 或下划线 (_),则该字符串被视为有效标识符。有效的标识符不能以数字开头,也不能包含任何空格。

            因此,如果这符合您的要求,那么 isidentifier 将快速且易于使用。

            有人提到了正则表达式的效率,我很好奇:

            import timeit
            
            setup='import re; rs="\s"; rc=re.compile(rs); s="applebananacanteloupe"'
            stm1='re.search(rs,s)'
            stm2='re.search(rc,s)'
            stm3='" " in s'
            stm4='s.isidentifier()'
            
            timeit.repeat(stm1,setup)
            # result: [0.9235025509842671, 0.8889087940042373, 0.8771460619755089, 0.8753634429886006, 1.173506731982343]
            
            timeit.repeat(stm2,setup)
            # results: [1.160843407997163, 1.1500899779784959, 1.1857644470001105, 1.1485740720236208, 1.2856045850203373]
            # compiled slower than uncompiled? Hmm, I don't get regex...
            
            timeit.repeat(stm3,setup)
            # [0.039073383988579735, 0.03403249100665562, 0.03481135700712912, 0.034628107998287305, 0.03392893000273034]
            
            timeit.repeat(stm4,setup)
            # [0.08866660299827345, 0.09206177099258639, 0.08418851799797267, 0.08478381999884732, 0.09471498697530478]
            
            

            所以,isidentifier 几乎和in 一样快,比正则表达式快 10 倍。请注意,从技术上讲,不能保证 python 关于标识符的概念不会改变 - 但如果改变了,您的代码也可能需要重新修改。

            【讨论】:

              猜你喜欢
              • 2010-12-16
              • 2017-08-19
              • 2014-08-03
              • 1970-01-01
              • 1970-01-01
              • 2011-01-25
              • 2022-06-25
              • 2015-06-12
              相关资源
              最近更新 更多