[Tutor] string split function - how to tell how many splits
Joel Goldstick
joel.goldstick at gmail.com
Tue Nov 8 18:04:48 CET 2011
On Tue, Nov 8, 2011 at 11:56 AM, Cranky Frankie <cranky.frankie at gmail.com>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[0]) # print the first one
> print (new_list[1]) # print the second one
> print (new_list[2]) # print the third one
> print (new_list[3]) # print the fourth one
> print (new_list[4]) # 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?
>
>
>
> --
> Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA
> Risible Riding Raconteur & Writer
> Don't sweat the petty things, and don't pet the sweaty things.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
you can find the length of the list with the len() function
>>> field = 'The Good Wife ;' # a string separated by spaces
>>> new_list = field.split(' ') # create a list of space delimited
elements
>>> len(new_list)
4
--
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111108/c9cfa9f5/attachment.html>
More information about the Tutor
mailing list