-1

In python what code can I use in an if statement to check a string, after I did the .split code on it to see if there was only one string created?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user2848342
  • 47
  • 1
  • 11
  • If you've read the [documentation](http://docs.python.org/3/library/stdtypes.html) on string splitting in Python, and on [lists](http://docs.python.org/release/1.5.1p1/tut/lists.html) and existing answers on how to find the [length of a list](http://stackoverflow.com/questions/1712227/get-the-size-of-a-list-in-python), and are still puzzled, you could ask a more specific question. – Simon Oct 05 '13 at 00:57

3 Answers3

6

.split() returns a list, you can call the function len() on that list to get how many items `.split()' returns:

>>> s = 'one two three'
>>> s.split()
['one', 'two', 'three']
>>> lst = s.split()
>>> len(lst)
3
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
4

You can do something like this

if len(myString.split()) == 1:
   ...
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3
def main():
    str = "This is a string that contains words."
    words = str.split()
    word_count = len(words)
    print word_count

if __name__ == '__main__':
    main()

Fiddle: http://ideone.com/oqpV2h

Colin Basnett
  • 4,052
  • 2
  • 30
  • 49