简体   繁体   中英

Python: Replace characters in a string by position

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.

如果您想继续使用string,这是解决方案:

newhand = '{0}{1}{2}'.format(newhand[:i], r.choice(cardset), newhand[i + 1:])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM