[Tutor] accessing string in list

Jerry Hill malaclypse2 at gmail.com
Tue Jul 15 17:05:28 CEST 2008


On Tue, Jul 15, 2008 at 10:55 AM, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I have a list of labels for a data file,
>
> test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>
> I would like to get the string of the first value that is greater than a
> known value and the previous string.
>
> If I have 15.8, I would like to get the index of '20' and '15'.  I would
> also like to make sure that my known value falls in the range 4-40.
>
> I am having trouble with the mixed types.
>
> for i in range(len(test)):
>     if Field < int(test[i]):
>         print i

You can put your conversion into a try/except block and handle the exception:

test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
my_val = 15.8
for index, value in enumerate(test):
    try:
        if int(value) < my_val:
            print value
    except ValueError:
        pass


-- 
Jerry


More information about the Tutor mailing list