检查字符串中是否有空格

Mar*_*jus 28 python string

' ' in word == True
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ens 66

==优先于in,所以你实际上正在测试word == True.

>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
Run Code Online (Sandbox Code Playgroud)

但你根本不需要== True.if需要[ ' ' in word评估为真或假的东西] 并将评估为真还是假.所以,if ' ' in word: ...很好:

>>> ' ' in w
3: True
Run Code Online (Sandbox Code Playgroud)

  • 它不会匹配所有类型的空格:\n,\ r,'',...如果他需要匹配它们,最好使用re模块,并在\ s上使用匹配方法.它会做一个更好的标记器. (3认同)
  • 宠物编程:`... == True`或`...!= False`,或其任何变体. (2认同)
  • 顺便说一句,Jukka Suomela的解释比我的解释更正确.根据我的解释,你将在True中测试`word == True`然后测试''',这没有意义. (2认同)

Juk*_*ela 15

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)哪个不是你想要的.


Gui*_*ois 11

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

t = s.split(" ")
if len(t) > 1:
  print "several tokens"
Run Code Online (Sandbox Code Playgroud)

为了确保它匹配各种空间,您可以使用re模块:

import re
if re.search(r"\s", your_string):
  print "several words"
Run Code Online (Sandbox Code Playgroud)

  • 您不需要正则表达式来检查每种空格,只需省略您传递给 `s.split()` 的 `" "`,因为默认情况下包括所有空格:https://docs.python.org/ 3/library/stdtypes.html#str.split (2认同)