10

String replacement in Python is not difficult, but I want to do something special:

teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']
#replace 'test' with random item from animals
finalstr = ['dog fox dog monkey']

I write a very inefficient version:

from random import choice
import string
import re

teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']

indexes = [m.start() for m in re.finditer('test', 'test test test test')]
#indexes = [0, 5, 10, 15]
for i in indexes:
    string.replace(teststr, 'test', choice(animals), 1)

#Final result is four random animals
#maybe ['dog fox dog monkey']

It works, but I believe there is some simple method with REGULAR EXPRESSION which I am not familiar with.

3 Answers 3

13

Use a re.sub callback:

import re
import random

animals = ['bird','monkey','dog','fox']

def callback(matchobj):
    return random.choice(animals)

teststr = 'test test test test'
ret = re.sub(r'test', callback, teststr)
print(ret)

yields (for example)

bird bird dog monkey

The second argument to re.sub can be a string or a function (i.e. a callback). If it is a function, it is called for every non-overlapping occurrance of the regex pattern, and its return value is substituted in place of the matched string.

Sign up to request clarification or add additional context in comments.

2 Comments

I dont know who delete the "lambda" verson: re.sub(r'test', lambda m: random.choice(animals), teststr) Actually it seems to be more succinct.
@GabySolis I deleted it (it was my answer). I thought the answer was unneccesary since unutbu already answered your question some seconds before me, basically saying the same: use re.sub with a callback. But if you like it, I undelete my answer.
1

You can use re.sub:

>>> from random import choice
>>> import re
>>> teststr = 'test test test test'
>>> animals = ['bird','monkey','dog','fox']
>>> re.sub('test', lambda m: choice(animals), teststr)
'fox monkey bird dog'
>>> re.sub('test', lambda m: choice(animals), teststr)
'fox dog dog bird'
>>> re.sub('test', lambda m: choice(animals), teststr)
'monkey bird monkey monkey'

Comments

1

This would do the job:

import random, re
def rand_replacement(string, to_be_replaced, items):
    return re.sub(to_be_replaced, lambda x: random.choice(items), string )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.