Check if space is in a string

Question:

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

Asked By: Marijus

||

Answers:

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

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.

Answered By: Wayne Werner

== 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
Answered By: 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?

Answered By: Justin Ethier

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.
Answered By: 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
if re.search(r"s", your_string):
  print "several words"

Use this:

word = raw_input("Please enter a single word : ")
while True:
    if " " in word:
        word = raw_input("Please enter a single word : ")
    else:
        print "Thanks"
        break
Answered By: John Howard

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
Answered By: Teodor Pripoae
# The following would be a very simple solution.

print("")
string = input("Enter your string :")
noofspacesinstring = 0
for counter in string:
    if counter == " ":
       noofspacesinstring += 1
if noofspacesinstring == 0:
   message = "Your string is a single word" 
else:
   message = "Your string is not a single word"
print("")   
print(message)   
print("")

You can use the ‘re’ module in Python 3.
If you indeed do, use this:

re.search('s', word)

This should return either ‘true’ if there’s a match, or ‘false’ if there isn’t any.

Answered By: Flippette
def word_in(s):
   return " " not in s 
Answered By: elham sabah

You can see whether the output of the following code is 0 or not.

'import re
x='  beer   '
len(re.findall('s', x))
Answered By: user3665906

You mentioned whitespace in general, rather than just spaces. I stumbled upon a solution with isidentifier. Per W3 schools:

A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

So, if this matches your requirements, isidentifier is quick and easy to use.

Somebody mentioned efficiency of regex, and I was curious:

import timeit

setup='import re; rs="s"; rc=re.compile(rs); s="applebananacanteloupe"'
stm1='re.search(rs,s)'
stm2='re.search(rc,s)'
stm3='" " in s'
stm4='s.isidentifier()'

timeit.repeat(stm1,setup)
# result: [0.9235025509842671, 0.8889087940042373, 0.8771460619755089, 0.8753634429886006, 1.173506731982343]

timeit.repeat(stm2,setup)
# results: [1.160843407997163, 1.1500899779784959, 1.1857644470001105, 1.1485740720236208, 1.2856045850203373]
# compiled slower than uncompiled? Hmm, I don't get regex...

timeit.repeat(stm3,setup)
# [0.039073383988579735, 0.03403249100665562, 0.03481135700712912, 0.034628107998287305, 0.03392893000273034]

timeit.repeat(stm4,setup)
# [0.08866660299827345, 0.09206177099258639, 0.08418851799797267, 0.08478381999884732, 0.09471498697530478]

So, isidentifier is almost as fast as in, and 10x faster than regex. Note that there is technically no guarantee that python’s idea of what an identifier is won’t change – but it’s also likely that if it did, your code would need some rework anyway.

Answered By: Trevor Gross
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.