Py学习  »  Python

在Python中随机替换两个字符

Sarah • 3 年前 • 1224 次点击  

我有一根绳子

n = 'sophieMueller'

其中,我想用以下列表中的两个随机字符替换两个随机字符:

replace = [
    'X', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
]

像这样:s0phieM9eller

以下几点几乎起到了作用:

它会随机显示 n (例如:。 n[2] ( p ))并将其替换为随机的 list (例如:。 replace[6] ( 5 )).

n[randint(0, len(n))] = replace[randint(0, len(replace))]

print(''.join(n))

我唯一的问题是,当我想替换多个字符时,有时会出现错误。我猜这是因为他们试图在同一时间替换相同的标识?有什么解决办法吗?

n[randint(0, len(n))] = replace[randint(0, len(replace))]
n[randint(0, len(n))] = replace[randint(0, len(replace))]

对某些运行进行正确的输出,然后:

错误:

Traceback (most recent call last):
  File "/Users/x/Desktop/test.py", line 16, in <module>
    n[randint(0, len(n))] = replace[randint(0, len(replace))]
IndexError: list index out of range
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132160
 
1224 次点击  
文章 [ 1 ]  |  最新文章 3 年前