Python有选择地从字符串中替换字符

时间:2011-11-29 08:57:22

标签: python regex string

我有一个包含固定字符的字符串。我可以通过用另一个字符或字符串替换它来生成字符串的排列吗? 说,我有这样的事情:

designatedstring="u"
replacerstring="ough"
s="thruput"

我想输出如下:

l=["throughput","thrupought","throughpought"]

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:4)

更多itertools糖:

>>> parts = s.split(designatedstring)
>>> num = len(parts) - 1
>>> replacements = itertools.product([designatedstring, replacerstring], repeat=num)
>>> replacements = list(replacements)
>>> replacements.remove((designatedstring,) * num)
>>> for r in replacements:
...     print ''.join(itertools.chain(*zip(parts, r + ('',))))
...
thrupought
throughput
throughpought

如果您可以在结果中使用原始字符串,则可以省略4行和5行的丑陋转换。

答案 1 :(得分:0)

这是一种有趣的方法,虽然我仍然使用itertools解决方案。

请注意,您生成的字符串列表在道德上是二叉树:在字符串中的替换字符的每个实例中,您要么忽略它(“向左”)或替换它(“向右”)。因此,您可以从替换字符串中创建二叉树结构。走二叉树的树叶很容易。

class ReplacementTree(object):
    def __init__(self, s, src, target, prefix=""):
        self.leaf = src not in s
        if 1 == len(s.split(src, 1)):
            self.head, self.tail = s, ""
        else:
            self.head, self.tail = s.split(src, 1)
        self.prefix, self.src, self.target = prefix, src, target

    @property
    def value(self):
        if self.leaf:
            return self.prefix + self.head

    @property
    def left(self):
        if self.leaf:
            return None
        else:
            return ReplacementTree(self.tail, 
                                   self.src,
                                   self.target,
                                   prefix=self.prefix + self.head + self.src)

    @property
    def right(self):
        if self.leaf:
            return None
        else:
            return ReplacementTree(self.tail, 
                                   self.src,
                                   self.target,
                                   prefix=self.prefix + self.head + self.target)

def leaves(tree):
    if tree.leaf:
        yield tree.value
    else:
        for leaf in leaves(tree.left):
            yield leaf
        for leaf in leaves(tree.right):
            yield leaf

示例:

>>> x = repltree.ReplacementTree("thruput", "u", "ough")
>>> list(repltree.leaves(x))
['thruput', 'thrupought', 'throughput', 'throughpought']

答案 2 :(得分:-1)

根据您提问中的输入,这将生成所请求的列表:

s="thruput"
designatedstring="u"
replacerstring="ough"

l = []
for i in range(len(s)):
    if s[i] == designatedstring:
        l += [s[:i] + replacerstring + s[i + 1:]]

l += [s.replace(designatedstring, replacerstring)]