Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replace ith occurence of x with ith element in list


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

like image 424
Helga Avatar asked May 17 '11 15:05

Helga


People also ask

How do you find the nth occurrence of a character in a string in Python?

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.

How do you replace all occurrences of a regex pattern in a string in Python?

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.


2 Answers

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")
like image 126
Nix Avatar answered Sep 28 '22 05:09

Nix


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')
like image 34
bluepnume Avatar answered Sep 28 '22 05:09

bluepnume