[Tutor] Tutor Digest, Vol 50, Issue 9

Kent Johnson kent37 at tds.net
Wed Apr 9 15:00:29 CEST 2008


Gloom Demon wrote:
> Hello :-)
> 
> Can someone please explain to me ho can I find out how many elements are 
> there in one record of a list?

The len() function gives the length of a list.

> I have a txt file from which I read data into Python.
> 
> The file looks something like this:
> 
> 01 bla bla bla 23,15 2345,67
> 02 alb alb 2,4 890,1
> 03 bal bla alb lab 567,12345 87,45
> ....
> 
> I need to be able to discriminate the string parts from the numeric ones. 
> Since the number of words in the file can vary, I have to be able to find out when they are finished 
> and when the floats come in

You can also use slice indexing with negative numbers to index from the end:

In [50]: data = '''01 bla bla bla 23,15 2345,67
    ....: 02 alb alb 2,4 890,1
    ....: 03 bal bla alb lab 567,12345 87,45
    ....: '''.splitlines()
In [51]: for line in data:
    ....:     line = line.split() # Break the line at whitespace
    ....:     print len(line) # Number of elements in the line
    ....:     print line[1:-2]
    ....:     print line[-2:]
    ....:     print
    ....:
    ....:
6
['bla', 'bla', 'bla']
['23,15', '2345,67']

5
['alb', 'alb']
['2,4', '890,1']

7
['bal', 'bla', 'alb', 'lab']
['567,12345', '87,45']

Negative indices index from the end of the list, so
   line[1:-2]
gives you the elements from line[1] up to but not including line[-2] 
which is the next-to-last element.

Kent


More information about the Tutor mailing list