1

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))
2
  • Why not keep it as a list instead of as a string? Then you could just do newhand[i] = r.choice(cardset) Commented Mar 28, 2013 at 3:44
  • strings are immutable. Create a new one Commented Mar 28, 2013 at 3:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I get this error with that solution: TypeError: 'str' object does not support item assignment
@user2218235 use the second solution if you want to keep hand as a string.
1

If you want to continue with string yet, this is the solution:

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

Comments

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)

3 Comments

Only if hand is a list, which it is not in his program.
you cannot convert a list to a string using str.
and this is why I shouldn't be doing this late at night... my apologies, answer has been updated to use join.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.