Python:用列表中的第i个元素替换第n次出现的x

时间:2011-05-17 15:35:47

标签: python string replace loops substitution


假设我们有a = "01000111000011"字符串n=5 "1" ith "1",我想用"ORANGE"中的 ith 字符替换。 我的结果应该是这样的:

b = "0O000RAN0000GE"

在Python中解决此问题的最佳方法是什么?是否可以将索引绑定到每个替换?

非常感谢! 海尔加

5 个答案:

答案 0 :(得分:6)

大量的答案/方法。我使用一个基本假设,即你的#of 1s等于你所取代的单词的长度。

a = "01000111000011"
a = a.replace("1", "%s")
b = "ORANGE"
print a % tuple(b)

或pythonic 1衬垫;)

print "01000111000011".replace("1", "%s") % tuple("ORANGE")

答案 1 :(得分:5)

a = '01000111000011'
for char in 'ORANGE':
  a = a.replace('1', char, 1)

或者:

b = iter('ORANGE')
a = ''.join(next(b) if i == '1' else i for i in '01000111000011')

或者:

import re
a = re.sub('1', lambda x, b=iter('ORANGE'): b.next(), '01000111000011')

答案 2 :(得分:3)

s_iter = iter("ORANGE")
"".join(next(s_iter) if c == "1" else c for c in "01000111000011")

答案 3 :(得分:0)

如果源字符串中的1的数量与替换字符串的长度不匹配,则可以使用此解决方案:

def helper(source, replacement):
    i = 0
    for c in source:
        if c == '1' and i < len(replacement):
            yield replacement[i]
            i += 1
        else:
            yield c

a = '010001110001101010101'
b = 'ORANGE'
a = ''.join(helper(a, b)) # => '0O000RAN000GE01010101'

答案 4 :(得分:0)

改进bluepnume的解决方案:

>>> from itertools import chain, repeat
>>> b = chain('ORANGE', repeat(None))
>>> a = ''.join((next(b) or c) if c == '1' else c for c in '010001110000110101')
>>> a
'0O000RAN0000GE0101'

[编辑]

甚至更简单:

>>> from itertools import chain, repeat
>>> b = chain('ORANGE', repeat('1'))
>>> a = ''.join(next(b) if c == '1' else c for c in '010001110000110101')
>>> a
'0O000RAN0000GE0101'

[编辑]#2

这也有效:

import re
>>> r = 'ORANGE'
>>> s = '010001110000110101'
>>> re.sub('1', lambda _,c=iter(r):next(c), s, len(r))
'0O000RAN0000GE0101'