1

尝试仅按位置替换字符串中的字符。

这是我所拥有的,任何帮助将不胜感激!

for i in pos:
    string=string.replace(string[i],r.choice(data))
4

3 回答 3

2

为什么不直接更换呢?

for i in pos:
    newhand=newhand.replace(newhand[i],r.choice(cardset))

去:

for i in pos:
    newhand[i]=r.choice(cardset)

这是假设这hand是一个列表而不是字符串。
如果hand是程序中此时的字符串,
我建议将其保留为列表,因为字符串无法更改,因为它们是不可变的

如果你想保持手作为一个字符串,你总是可以这样做:

newhand = ''.join([(x,r.choice(cardset))[i in pos] for i,x in enumerate(newhand)])

但这将转换newhand为一个列表,然后将其加入一个字符串,然后再将其存储回newhand.

此外,该行:

if isinstance(pos, int):
                pos=(pos,)

应改为:

pos = [int(index) for index in pos.split(',')]

您不需要isinstance,因为那将始终返回 false。

于 2013-03-28T03:46:03.357 回答
1

如果您还想继续使用字符串,这就是解决方案:

newhand = '{0}{1}{2}'.format(newhand[:i], r.choice(cardset), newhand[i + 1:])
于 2013-03-28T03:56:54.747 回答
1

您的问题在于替换功能。当您调用 replace 函数时,它会将第一个参数的所有实例替换为第二个参数。

因此,如果 newhand = AKAK9,newhand.replace("A","Q") 将导致 newhand = QKQK9。

如果可能,将字符串更改为列表,然后执行以下操作以更改特定索引:

for i in pos:
    newhand[i]=r.choice(cardset)

如果需要,您可以使用 str() 将 newhand 列表更改回字符串:

hand = ''.join(str(e) for e in newhand_list)
于 2013-03-28T03:59:07.507 回答