http://paste.pocoo.org/show/240061/ 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..

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

This is more idiomatic python - comparison against True or False is not necessary - just use the value returned by the expression ' ' in word.

Also, you don't need to use pastebin for such a small snippet of code - just copy the code into your post and use the little 1s and 0s button to make your code look like code.

Wayne Werner
+5  A: 

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

Rob Lourens
It won't match all kinds of spaces : \n, \r, ' ', ... If he needs to match them, it's better to use re module, with the match method on \s. It will do a better tokenizer.
Guillaume Lebourgeois
Programming pet peeve: `... == True` or `... != False`, or any variant thereof.
Jukka Suomela's explanation is a little more correct than mine, by the way. By my explanation, you'd be testing `word==True` then `' ' in True`, which doesn't make sense.
Rob Lourens

You can say word.strip(" ") to remove any leading/trailing spaces from the string - you should do that before your if statement. That way if someone enters input such as " test " your program will still work.

That said, if " " in word: will determine if a string contains any spaces. If that does not working, can you please provide more information?

Justin Ethier
+3  A: 

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


  • 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.
Jukka Suomela

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
m = re.match("\s", your_string, re.M)
if m:
  print "several words"
Guillaume Lebourgeois

Use this:

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

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
    print False
Teodor Pripoae
`mystring.find(' ') != -1` **is** boolean.
I.e., this can be shortened to `print mystring.find(' ') != -1`
Tim Pietzcker