Trying to replace characters in a string only by position.
Here is what I have, any help would be appreciated!
for i in pos:
string=string.replace(string[i],r.choice(data))
Why not just replace it directly?
for i in pos:
newhand=newhand.replace(newhand[i],r.choice(cardset))
goes to:
for i in pos:
newhand[i]=r.choice(cardset)
This is assuming that hand is a list and not a string.
If hand is a string at this point in the program,
I would recommend keeping it as a list, as strings are not able to be changed because they are immutable
If you want to keep hand as a string, you could always do:
newhand = ''.join([(x,r.choice(cardset))[i in pos] for i,x in enumerate(newhand)])
But this will convert newhand to a list and then join it into a string before storing it back into newhand.
Also, The line:
if isinstance(pos, int):
pos=(pos,)
should be changed to:
pos = [int(index) for index in pos.split(',')]
You don't need isinstance because that will always return false.
hand as a string.Your problem is with the replace function. When you call the replace function it replaces ALL instances of the first argument with the second argument.
so, if newhand = AKAK9, newhand.replace("A","Q") will result in newhand = QKQK9.
If possible, change the string to a list, then do the following to change the specific index:
for i in pos:
newhand[i]=r.choice(cardset)
If needed, you can then change the newhand list back to a string by using str():
hand = ''.join(str(e) for e in newhand_list)
hand is a list, which it is not in his program.list to a string using str.
newhand[i] = r.choice(cardset)