-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
  • 51,252
  • 26
  • 196
  • 186
user2848342
  • 47
  • 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
  • 34,189
  • 11
  • 57
  • 87
4

You can do something like this

if len(myString.split()) == 1:
   ...
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
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
  • 3,931
  • 2
  • 28
  • 47