Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if space is in a string

Tags:

python

string

' ' 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..

like image 666
Marijus Avatar asked Jul 21 '10 16:07

Marijus


People also ask

How do I check if a string contains a space?

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.

How do you check if a string contains a space in C++?

The isspace() function in C++ checks if the given character is a whitespace character or not.

How do you check if a character in a string is a space in Java?

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.


2 Answers

== 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 
like image 195
Rob Lourens Avatar answered Sep 26 '22 17:09

Rob Lourens


Write if " " in word: instead of if " " in word == True:.

Explanation:

  • In Python, for example a < b < c is equivalent to (a < b) and (b < c).
  • The same holds for any chain of comparison operators, which include in!
  • Therefore ' ' in w == True is equivalent to (' ' in w) and (w == True) which is not what you want.
like image 42
Jukka Suomela Avatar answered Sep 22 '22 17:09

Jukka Suomela