-2

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

Thanks!

Hexbob6
  • 167
  • 1
  • 2
  • 12

2 Answers2

6

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".

declension
  • 4,110
  • 22
  • 25
1

No there don't exsist any mechanism of the shelf like this.

If your only aim is to find if it's only one word or there exsit another word it can be done by :

x = 'has words'
' ' in x
>>> True
harshil9968
  • 3,254
  • 1
  • 16
  • 26