lucaconlaq
lucaconlaq

Reputation: 1541

how to replace all the occurrence in a string with a different number

I have never used python in my life. I need to make a little fix to a given code.

I need to replace this

 new_q = q[:q.index('?')] + str(random.randint(1,rand_max)) + q[q.index('?')+1:]

with something that replace all of the occurrence of ? with a random, different number.

how can I do that?

Upvotes: 3

Views: 1428

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601529

If you need all the numbers to be different, just using a new random number for each occurrence of ? won't be enough -- a random number might occur twice. You could use the following code in this case:

random_numbers = iter(random.sample(range(1, rand_max + 1), q.count("?")))
new_q = "".join(c if c != "?" else str(next(random_numbers)) for c in q)

Upvotes: 2

eumiro
eumiro

Reputation: 212835

import re
import random
a = 'abc?def?ghi?jkl'
rand_max = 9

re.sub(r'\?', lambda x:str(random.randint(1,rand_max)), a)

# returns 'abc3def4ghi6jkl'

or without regexp:

import random
a = 'abc?def?ghi?jkl'
rand_max = 9
while '?' in a:
    a = a[:a.index('?')] + str(random.randint(1,rand_max)) + a[a.index('?')+1:]

Upvotes: 5

Related Questions