Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8304

Python • find() function behavior

$
0
0
I have written the following code to scan through a line of text and return the index of the key strings that exist in the scan string

What I want it to do:
1. Return ALL the instances of the key string
2. Return the key string and location index in variables such as key1/index1, key2/ndex2, ETC

What it does now:
1. return the FIRST instance of each key string found


I haven't found away to return the key/index pair. The only thing I thought was to provide a list structure indexlist[] and keylist[] then separate them into individual variables, but that isn't very clean.

Code:

#the purpose of the routine is to explore the boundary cases in# the python for() loop#          0123456789012345678901234567890123434567890        line_in = "Emerson Lake and Palmer met on a Lake Swamp"keys = ['Stream', 'Lake','Pond','Swamp']Flag = 'NO'for key in keys:    index1 = line_in.find(key)    if(index1 != -1):        print('found '+ key + ' at index ' + str(index1))         Flag = 'YES'if(Flag == 'NO'): print('No Water Bodies Found')

Statistics: Posted by ras_oscar — Fri Aug 15, 2025 3:15 pm



Viewing all articles
Browse latest Browse all 8304

Trending Articles