【问题标题】:Replace every single Character with a random Letter from a list用列表中的随机字母替换每个字符
【发布时间】:2020-08-27 17:56:24
【问题描述】:
Replace_Character = input("Enter ! here: ")
Replace_Character = Replace_Character.replace("!",random.choice(Letters))

当我运行它时,它确实替换了 !带有列表中的随机字母,但字母都相同。我怎么能做到这样!再收到一封信?

【问题讨论】:

  • 请添加您的完整代码。
  • replace 函数将第一个参数的所有实例替换为第二个参数。您将不得不使用不同的方式,而不仅仅是一个衬里,以便能够用不同的字母更改每个实例。

标签: python python-3.x random replace


【解决方案1】:

这里我使用了一个生成器表达式,并假设你想随机抽样并替换:

>>> import string
>>> import random
>>> letters = string.ascii_lowercase
>>> print(letters)
abcdefghijklmnopqrstuvwxyz
>>> test = '!A!B!!'
>>> ''.join(random.choice(letters) if c == '!' else c for c in test)
'uAqBtq'
>>> ''.join(random.choice(letters) if c == '!' else c for c in test)
'xApBfo'

【讨论】:

  • 我试过了,但不知何故不起作用。不过感谢您的帮助。
  • 你能解释一下什么“不起作用”吗?这正是您所要求的。
【解决方案2】:

Chris 的解决方案有效,我想提供一些背景信息说明为什么您的解决方案无效。

Replace_Character = Replace_Character.replace("!",random.choice(Letters))

为了评估这一点,Python 需要找出调用 str.replace() 时使用的参数。它知道第一个参数是"!",但它需要评估第二个参数。所以它首先执行random.choice(Letters)。假设它收到了q 的字母。然后,它调用 Replace_Character.replace("!", "q")。您可以看到每次都将其设置为相同的字符。

单行字符串生成器技巧很简洁,但可能难以理解或难以阅读。这是 Chris 的答案的等价物,用普通的 for 循环编写。

new_string = ""
for character in old_string:
    if (character == "!"):
        # generate a random letter to replace the ! with
        new_string += random.choice(Letters)
    else:
        # copy the old text, unmodified
        new_string += character

【讨论】:

  • (Python 中的字符串是不可变的,这意味着这可能会比像 Chris' 这样的解决方案性能更差,但我认为它最清楚地说明了正在发生的事情,这在这里似乎很重要)
猜你喜欢
  • 2015-07-05
  • 1970-01-01
  • 2012-06-24
  • 2017-08-06
  • 2017-08-10
  • 1970-01-01
  • 2021-05-18
  • 2017-05-20
  • 1970-01-01
相关资源
最近更新 更多