python -regular expression - list element

Matimus mccredie at
Wed Jun 25 18:35:00 CEST 2008

On Jun 25, 2:55 am, antar2 <desoth... at> wrote:
> Hello,
> I am a beginner in Python and am not able to use a list element for
> regular expression, substitutions.
> list1 = [ 'a', 'o' ]
> list2 = ['star',  'day', 'work', 'hello']
> Suppose that I want to substitute the vowels from list2 that are in
> list1, into for example 'u'.
> In my substitution, I should use the elements in list1 as a variable.
> I thought about:
> for x in list1:
>    re.compile(x)
>         for y in list2:
>            re.compile(y)
>                 if x in y:
>                         z = re.sub(x, 'u', y)
> but this does not work

Others have given you several reasons why that doesn't work. Nothing I
have seen will work for words which contain both 'a' and 'o' however.
The most obvious way to do that is probably to use a re:

>>> words = ['star', 'day', 'work', 'hello', 'halo']
>>> vowels = [ 'a', 'o' ]
>>> import re
>>> vp = re.compile('|'.join(vowels))
>>> [vp.sub('u', w) for w in words]
['stur', 'duy', 'wurk', 'hellu', 'hulu']

However, the fastest way is probably to use maketrans and translate:

>>> from string import maketrans, translate
>>> trans = maketrans(''.join(vowels), 'u'*len(vowels))
>>> [translate(w, trans) for w in words]
['stur', 'duy', 'wurk', 'hellu', 'hulu']


More information about the Python-list mailing list