Check if space is in a string

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

12 Answers

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.

# 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("")
def word_in(s):
   return " " not in s 

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

'import re
x='  beer   '
len(re.findall('\s', x))

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.

Related