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

标签 python replace

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/

相关文章:

linux - 仅打开包含特定字符串的文件,然后在 Linux 命令行上替换

python - Pandas Groupby 按递减顺序替换值

python - 用 2 个生成器替换 3 个列表

如果 value = something,Mysql 替换行

python - Pyramid 和 python 请求库之间的奇怪行为

python - python3 open "x"模式有什么作用?

javascript - 替换 javascript 字符串中的 ${...} 吗?

list - flutter 。 Dart 。 Flutter - 替换列表中的项目

python - 如何根据pandas中的时差为用户设置 session

python - Python 的 hashlib.sha256(x).hexdigest() 是否等同于 Rs digest(x,algo ="sha256")