Checking if string starts with list element

Rob Hooft rob at hooft.net
Tue Aug 15 03:18:39 EDT 2000


>>>>> "SB" == Simon Brunning <SBrunning at trisystems.co.uk> writes:

 SB> I have a list of strings: romans = ['aqueduct', 'sanitation',
 SB> 'roads', 'irrigation', 'medicine', 'education', 'wine', 'public
 SB> baths', 'order']

 SB> And I have a single string: us = 'wine, women and song.'

 SB> I want to know whether my sting *starts with* one of the strings
 SB> in my list. The best that I can do is something like:

I'd construct a regular expression:

romans = ['aqueduct', 'sanitation', 'roads', 'irrigation', 'medicine', 
          'education', 'wine', 'public baths', 'order']
us = 'wine, women and song.'
# Only once.
import string,re
R=re.compile('('+string.join(romans,'|')+')')
# Every time
m=R.match(us)
if m:
    print m.group(1)

-- 
=====   rob at hooft.net          http://www.hooft.net/people/rob/  =====
=====   R&D, Nonius BV, Delft  http://www.nonius.nl/             =====
===== PGPid 0xFA19277D ========================== Use Linux! =========



More information about the Python-list mailing list