\' \' in word == True
I\'m writing a program that checks whether the string is a single word. Why doesn\'t this work and is there any better way to che
Write if " " in word:
instead of if " " in word == True:
.
Explanation:
a < b < c
is equivalent to (a < b) and (b < c)
.in
!' ' in w == True
is equivalent to (' ' in w) and (w == True)
which is not what you want.You can try this, and if it will find any space it will return the position where the first space is.
if mystring.find(' ') != -1:
print True
else:
print False
There are a lot of ways to do that :
t = s.split(" ")
if len(t) > 1:
print "several tokens"
To be sure it matches every kind of space, you can use re module :
import re
if re.search(r"\s", your_string):
print "several words"
==
takes precedence over in
, so you're actually testing word == True
.
>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
But you don't need == True
at all. if
requires [something that evalutes to True or False] and ' ' in word
will evalute to true or false. So, if ' ' in word: ...
is just fine:
>>> ' ' in w
3: True