简体   繁体   中英

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?

Try this:

line = 'how are you?'

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

获得line.split()似乎更pythonic,但如果这将是一个昂贵的操作,这可能会更快:

if ' ' in 'how are you?': line.split()
line.strip().count(' ') > 0 # finds at least one separator after removing the spaces at the left and the right of the actual string

或者如果你真的想要速度

line.strip().find(' ') != -1 # not finding the ' ' character in the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM