gpt4 book ai didi

python - 如何替换句子中除一个字符外的所有字符

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:42 24 4
gpt4 key购买 nike

sentence = “This makes array operations faster but less safe”

letter = ‘a’

函数必须打印

******a****a**a******a*******a***************a**

我尝试过使用替换和其他方法,但我仍然没有找到使它工作的方法

spam="This makes array operations faster but less safe"

print(spam.replace("b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", "*"))

我很期待

******a****a**a******a*******a***************a**

最佳答案

使用正则表达式。

例如:

import re
sentence = 'This makes array operations faster but less safe'
print(re.sub(r"[^a]", r"*", sentence))

输出:

******a****a**a******a*******a***************a**

关于python - 如何替换句子中除一个字符外的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com