社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Alexandre B.

Alexandre B. 最近创建的主题
Alexandre B. 最近回复了
5 年前
回复了 Alexandre B. 创建的主题 » 为什么replace()在我的Python函数中不起作用?[副本]

你只需要原谅在你的循环中保存价值。这个 replace 方法返回字符串。

def replace_exception_chars(string):
    exception_chars_dict = {'Old': 'New', 'old': 'new'}
    exception_chars_keys = list(exception_chars_dict.keys())
    for exception_char in exception_chars_keys:
        if exception_char in string:
            string = string.replace(
                exception_char, exception_chars_dict[exception_char])
    return string


print(replace_exception_chars('Old, not old'))
# New, not new