Hel*_*lga 5 python string loops replace substitution
假设我们有一个a = "01000111000011"带n=5 "1"s 的字符串.第i个 "1",我想替换为第i个角色"ORANGE".我的结果应该是这样的:
b = "0O000RAN0000GE"
Run Code Online (Sandbox Code Playgroud)
什么是在Python中解决这个问题最好的方法?是否可以将索引绑定到每个替换?
非常感谢!海尔格
大量的答案/方法来做到这一点.我使用一个基本假设,即你的#of 1s等于你所取代的单词的长度.
a = "01000111000011"
a = a.replace("1", "%s")
b = "ORANGE"
print a % tuple(b)
Run Code Online (Sandbox Code Playgroud)
或pythonic 1衬垫;)
print "01000111000011".replace("1", "%s") % tuple("ORANGE")
Run Code Online (Sandbox Code Playgroud)
a = '01000111000011'
for char in 'ORANGE':
a = a.replace('1', char, 1)
Run Code Online (Sandbox Code Playgroud)
要么:
b = iter('ORANGE')
a = ''.join(next(b) if i == '1' else i for i in '01000111000011')
Run Code Online (Sandbox Code Playgroud)
要么:
import re
a = re.sub('1', lambda x, b=iter('ORANGE'): b.next(), '01000111000011')
Run Code Online (Sandbox Code Playgroud)