Hexbob6 Hexbob6 - 1 year ago 219
Python Question

Python - Check if a string contains multiple words

I'm wondering if there was a function in Python 2.7 that checks to see if a string contains multiple words (as in words with spaces/punctuation marks between them), similar to how

checks to see if a string contains only letters?

For example, if something along the lines of this exists...

var_1 = "Two Words"

if var_1.containsmultiplewords():
print "Yes"

And then "Yes" would be the output.


Answer Source

Basic implementation

Generally, you use split() to split a string of words into a list of them. If the list has more than one element, it's True (i.e. you could print yes)

def contains_multiple_words(s):
  return len(s.split()) > 1

Punctuation support

To support punctuation etc as well, you can split on a regular expression, via the re module's split command:

import re

def contains_multiple_words(s):
  return len(re.compile('\W').split(s)) > 1

The regular expression character class \W means any single non-word character, e.g. punctuation or spaces (see the Python regex syntax guide for details).

Thus, splitting on this instead of just space (the default in the first example) allows for a more realistic idea of "words".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download