[Tutor] string split function - how to tell how many splits
steve at pearwood.info
Tue Nov 8 18:06:44 CET 2011
Cranky Frankie wrote:
> How do you tell how many splits the string split funtion returns? For example:
> field = 'The Good Wife ;' # a string separated by spaces
> new_list = field.split(' ') # create a list of space delimited elements
> print (new_list) # print the first one
> print (new_list) # print the second one
> print (new_list) # print the third one
> print (new_list) # print the fourth one
> print (new_list) # print the fifth one
> The last line above causes an error. I plan on reading in a file where
> I don't know what the number of splits will be. How can I find out
> before trying to access an out of range index?
text = 'Nobody expects the Spanish Inquisition!!!'
words = text.split(' ')
number_of_words = len(words)
print words[number_of_words - 1] # prints "Inquisition!!!"
More information about the Tutor