' ' 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 check if a string has no spaces/is a single word..
Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.
The isspace() function in C++ checks if the given character is a whitespace character or not.
The isWhitespace(char ch) method returns a Boolean value, i.e., true if the given(or specified) character is a Java white space character. Otherwise, this method returns false.
==
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
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With