The string replace function takes an optional count argument to control the maximum number of replacements to make
"This is an awesome string".replace("a","@") # "This is @n @wesome string"
"This is an awesome string".replace("a","@",1) # "This is @n awesome string"
If you need to do it at random, we can write a function to do that
import random
def randreplace(str,c,c_replace,maxnum=0):
if maxnum >= str.count(c) or maxnum<1:
return str.replace(c,c_replace)
indices = [i for i,x in enumerate(str) if x==c]
replacements = random.sample(indices,maxnum)
st_pieces = (x if not i in replacements else c_replace for i,x in enumerate(str))
return "".join(st_pieces)
This function takes the string to do the replacements in, the character to replace, the character to replace it with, and the maximum number of replacements (0 for all of them) and returns the string with the desired number of replacements done at random.
random.seed(100)
randreplace("This is an awesome string","a","@",1) # "This is @n awesome string"
randreplace("This is an awesome string","a","@",1) # "This is an @wesome string"
randreplace("This is an awesome string","a","@",2) # "This is @n @wesome string"
randreplace("This is an awesome string","a","@") # "This is @n @wesome string"