Determine whether there’s more than one word in a string
11,175
Solution 1
Try this:
line = 'how are you?'
if len(line.split()) > 1: # has more than 1 word
Solution 2
Getting the line.split() seems more pythonic, but if that was going to be an expensive operation, this might be faster:
if ' ' in 'how are you?': line.split()
Solution 3
line.strip().count(' ') > 0 # finds at least one separator after removing the spaces at the left and the right of the actual string
or if you really want speed
line.strip().find(' ') != -1 # not finding the ' ' character in the string
Author by
Charlie Baker
Updated on June 14, 2022Comments
-
Charlie Baker almost 2 years
For example:
line = 'how are you?' if line == [has more than one word]: line.split()
Is this possible?
-
Padraic Cunningham over 9 years
" foo " == True
"foo " == True
-
Ngenator over 9 yearsIt's 6x faster than
line.count(' ')
and 9x faster thanif len(line.split())
in 2.7 -
Padraic Cunningham over 9 yearsyou can have a space after a word and before a single word
-
Jared Windover-Kroes over 9 yearsOoh good point! @Padraic. Depending on how you're getting the input, a lstrip and/or an rstrip could be prudent.
-
Ry- over 9 years
.lstrip().rstrip()
is just.strip()
, and' ' in line.strip()
is easier. -
steveha over 9 yearsThis answer is best because it handles any kind of whitespace... it would also produce a correct result for
"how\tare\tyou"
, which separates the words with tabs, for example.