Python: Replace the i-th occurrence of x with the i-th element in the list


Suppose we have a string a = "01000111000011"with n=5 "1"s. I "1", I would like to replace with the i-th character in "ORANGE". My result should look like this:

b = "0O000RAN0000GE"

What could be the best way to solve this problem in Python? Is it possible to bind an index to each lookup?

Many thanks! Helga

+5
source share
5 answers

Tons of answers / ways to do this. Mine uses the fundamental assumption that your #of 1s is equal to the length of the word you are putting off.

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

Or pythonic 1 liner;)

print "01000111000011".replace("1", "%s") % tuple("ORANGE")
+6
source
a = '01000111000011'
for char in 'ORANGE':
  a = a.replace('1', char, 1)

Or:

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

Or:

import re
a = re.sub('1', lambda x, b=iter('ORANGE'): b.next(), '01000111000011')
+5
source
s_iter = iter("ORANGE")
"".join(next(s_iter) if c == "1" else c for c in "01000111000011")
+3

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'

[EDIT]

:

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

[EDIT] # 2

:

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

All Articles