str.find for multiple strings

Dave K dk123456789 at REMOVEhotmail.com
Wed Feb 11 19:02:12 EST 2004


On Wed, 11 Feb 2004 14:48:22 -0500 in comp.lang.python, Bart Nessux
<bart_nessux at hotmail.com> wrote:

>Peter Hansen wrote:
>> Bart Nessux wrote:
>> 
>>>x = str.find(temp, '120.50')
>>>
>>>I am looking for '120.50' '120.51' '122.78' etc. How can I do this with
>>>just one str.find... I can use re if I must, but I'd like to avoid it if
>>>possible.
>> 
>> 
>> In addition to Fecundo's questions, here's another.  What does "temp"
>> contain?  A single temperature string, or a temperature embedded in
>> a bunch of other stuff, or a whole series of temperatures, or what?
>> 
>> -Peter
>
>Here's what I'm doing
>
>def exclude():
>    import os
>    os.chdir('/home/rbt/scripts')
>    inputFile = file('ath_ips.txt', 'r')
>    data = inputFile.read()
>    inputFile.close()
>    comment = '#'
>    net0 = '128.173.120.'
>    net1 = '128.173.122.'
>    host0 = ['50','51','52','53','54','55']
>    host1 = ['17','25','49','50','55','58','70']
>    for h0 in host0:
>       h0 = net0+h0
>       rep0 = comment+h0
>       sea0 = str.find(data, h0)
>       if sea0 >=0:
>          data = data.replace(h0, rep0)
>    for h1 in host1:
>       h1 = net1+h1
>       rep1 = comment+h1
>       sea1 = str.find(data, h1)
>       if sea1 >=0:
>          data = data.replace(h1, rep1)
>    outputFile = file('ath_ips.txt', 'w')
>    outputFile.write(data)
>    outputFile.close()
>

There's no need to do an explicit find() before replace(). Your 'for'
loops can be written as

   for h0 in host0:
      data = data.replace(net0+h0, comment+net0+h0)
   for h1 in host1:
      data = data.replace(net1+h1, comment+net1+h1)


Or reduce it to one 'for' loop with list_comprehensions

   for host in [net0+h0 for h0 in host0] + [net1+h1 for h1 in host1]:
      data = data.replace(host, comment+host)

Dave



More information about the Python-list mailing list