Suppose we have a string a = "01000111000011"
with n=5 "1"
s. The ith "1"
, I would like to replace with the ith character in "ORANGE"
.
My result should look like:
b = "0O000RAN0000GE"
What could be the finest way to solve this problem in Python? Is it possible to bind an index to each substitution?
Many thanks! Helga
You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.
sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.
Tons of answers/ways to do it. Mine uses a fundamental assumption that your #of 1s is equal to the length of the word you are subsituting.
a = "01000111000011"
a = a.replace("1", "%s")
b = "ORANGE"
print a % tuple(b)
Or the pythonic 1 liner ;)
print "01000111000011".replace("1", "%s") % tuple("ORANGE")
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With