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
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.
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 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?
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
# 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.
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"
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.Source: Stackoverflow.com