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
Share:
11,175
Charlie Baker
Author by

Charlie Baker

Updated on June 14, 2022

Comments

  • Charlie Baker
    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
    Padraic Cunningham over 9 years
    " foo " == True "foo " == True
  • Ngenator
    Ngenator over 9 years
    It's 6x faster than line.count(' ') and 9x faster than if len(line.split()) in 2.7
  • Padraic Cunningham
    Padraic Cunningham over 9 years
    you can have a space after a word and before a single word
  • Jared Windover-Kroes
    Jared Windover-Kroes over 9 years
    Ooh good point! @Padraic. Depending on how you're getting the input, a lstrip and/or an rstrip could be prudent.
  • Ry-
    Ry- over 9 years
    .lstrip().rstrip() is just .strip(), and ' ' in line.strip() is easier.
  • steveha
    steveha over 9 years
    This 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.