私信  •  关注

Alexandre B.

Alexandre B. 最近创建的主题
Alexandre B. 最近回复了
6 年前
回复了 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