Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 540
Luka Avatar asked Nov 30 '25 10:11

Luka


2 Answers

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:]
like image 78
eumiro Avatar answered Dec 02 '25 23:12

eumiro


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)
like image 25
Sven Marnach Avatar answered Dec 02 '25 22:12

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!