替换字符串中子字符串的随机实例

时间:2013-11-04 16:47:34

标签: python

说我有字符串

s = 'x x x x x'

我想随机将'x'中的一个更改为y

s2 = 'x x y x x'

x和y将是多个字符长。

如果我只想更改x的第一个实例,我会使用string.replace,但是如何更改随机实例?

2 个答案:

答案 0 :(得分:4)

您可以使用re.finditer检索所有可能匹配项的开始/结束并进行适当的替换。这将涵盖变量长度替换,但确实意味着您需要警惕frm参数的重新语法。

import re
from random import choice

def replace_random(src, frm, to):
    matches = list(re.finditer(frm, src))
    replace = choice(matches)
    return src[:replace.start()] + to + src[replace.end():]

示例:

>>> [replace_random('x x x x x', r'\bx\b', 'y') for _ in range(10)]
['y x x x x', 'x x x x y', 'x x y x x', 'x y x x x', 'x x x y x', 'x x x y x', 'x x y x x', 'x y x x x', 'x x x x y', 'x x y x x']

答案 1 :(得分:2)

你可以做到

import random

def replace_random(string, str_a, str_b):
    rand = max(random.randint(0, string.count(str_a)), 1)
    return string.replace(str_a, str_b, rand).replace(str_b, str_a, rand - 1)

print replace_random('x x x x x', 'x', 'y')