2011-05-17 65 views
5


假設我們有一個字符串a = "01000111000011"n=5 "1" s。 第i個"1",我想用"ORANGE"中的個字符替換。 我的結果應該是這樣的:Python:用列表中的第i個元素替換x的出現次數

b = "0O000RAN0000GE" 

什麼可以解決在Python這個問題的最好方法是什麼?是否有可能綁定索引到每個替代?

非常感謝! 海爾格

回答

6

噸。我使用一個基本的假設,即你的#的1s等於你所代入的單詞的長度。

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

還是Python的1個襯墊;)

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

我喜歡那一行 – utdemir 2011-05-17 16:27:02

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') 
+0

這個答案的第一部分,而明確的,具有可怕的表現。如果此任務需要爲多個字符串完成,則不應使用它。 – 2011-05-17 17:16:49

+0

如果原始字符串中的1多於替換字符中的1(請參閱'010001110000110101010101'),此答案的第二部分將會出現問題。 – 2011-05-17 17:26:44

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

如果原始字符串中的字符數多於替換字符中的字符數(請參閱'010001110000110101010101'),此答案將會出現問題。 – 2011-05-17 17:27:22

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' 
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'