python - 如何在Python中不使用replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?

标签 python python-3.x for-loop

这是我到目前为止所拥有的,但为了替换 a、b 和 c,我想知道如何合并替换句子中所有出现的所有 3 个字母。我也不允许使用replace()函数。

def changeLetters(word):
    for letter in word:
        if letter == "a": #I would like to replace a,b and c
            word.replace(letter,"!") #replace the replace() function
    return word

用户输入示例:

Amy buys carrots and apples

用户输出示例:

!my 3uys 8!rrots !nd !pples

最佳答案

word = 'Amy buys carrots and apples'
result = ''.join(['!' if x == 'a' else '3' if x == 'b' else '8' if x == 'c' else x for x in word.lower()])
result
'!my 3uys 8!rrots !nd !pples'

关于python - 如何在Python中不使用replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886620/

相关文章:

python - 从属性包装方法返回修改后的文档字符串

python - 如何在调试日志中查看 Python 请求使用哪个 IP 地址进行连接?

python - 提取字典中的值

arrays - CoffeeScript:循环遍历数组中的对象

python - 如何使用正则表达式提取关键子串和 "/"之间的字符串?

python - Pandas - 其他每个值的列的最小值

python - 等号和函数参数的问题

python - 有没有办法在 Python (3) for 循环中做条件语句?

python 多处理示例 itertools 多个列表

python - python中的短代码