[Tutor] list.replace -- string.swap

Kent Johnson kent37 at tds.net
Tue Mar 17 13:54:25 CET 2009


On Tue, Mar 17, 2009 at 7:01 AM, spir <denis.spir at free.fr> wrote:
> Is there a list.replace builtin I cannot find? Or a workaround?

Just assign directly to list elements. To replace s1 with s2 in l:
for i, x in enumerate(l):
  if x == s1:
    l[i] = s2


> Also: How would perform string.swap(s1, s2) in the following cases:
>
> * There is no secure 'temp' char, meaning that
>        s.replace(s1,temp).replace(s2,s1).replace(temp,s2)
>  will fail because any char can be part of s.

You could use re.sub() with a function for the replacement string. It
takes a little setup but it's not really difficult:

import re

def string_swap(s, s1, s2):
    ''' Swap s1 and s2 in s'''

    # Given a match, return s2 for s1 and vice-versa
    def replace(m):
        return s2 if m.group()==s1 else s1

    # re to match s1 or s2
    matcher = re.compile('%s|%s' % (re.escape(s1), re.escape(s2)))
    return matcher.sub(replace, s)

print string_swap('go to the park', 'o', 'a')

Kent


More information about the Tutor mailing list