Charlie Baker
Charlie Baker

Reputation: 81

Determine whether there’s more than one word in a string

For example:

line = 'how are you?'

if line == [has more than one word]: line.split()

Is this possible?

Upvotes: 3

Views: 16923

Answers (3)

Gabriel
Gabriel

Reputation: 3594

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

Upvotes: 2

Jared Windover-Kroes
Jared Windover-Kroes

Reputation: 561

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()

Upvotes: 2

rlms
rlms

Reputation: 11060

Try this:

line = 'how are you?'

if len(line.split()) > 1: # has more than 1 word

Upvotes: 17

Related Questions