为什么 replace() 在我的 Python 函数中不起作用? [英] Why replace() doesn't work in my Python function?

查看:73
本文介绍了为什么 replace() 在我的 Python 函数中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际代码如下:

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.replace(exception_char, exception_chars_dict[exception_char])
    return string

print(replace_exception_chars('Old, not old'))

如果我试图运行它,我会在 OUTPUT 中得到未更改的源字符串.请看一看:

If I'm trying to run it I'm getting unchanged source string in OUTPUT. Please have a look:

更新所需的输出:

新的,不是新的

推荐答案

replace 不是就地方法,而是返回一个新字符串,因此您需要将结果分配给新字符串.

replace is not a in-place method, but instead it returns a new string, so you need to assign the result to a new string.

来自文档:https://docs.python.org/3/library/stdtypes.html#str.replace

str.replace(old, new[, count])
返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换.如果给出了可选参数计数,则仅替换出现的第一个计数.

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

如果你一起迭代键和值,你的逻辑也可以简化很多,如下所示

Also your logic can be simplified a lot like below, if you iterate on key and value together

def replace_exception_chars(string):
    exception_chars_dict = {'Old': 'New', 'old': 'new'}

    #Iterate over key and value together
    for key, value in exception_chars_dict.items():
        #If key is found, replace key with value and assign to new string
        if key in string:
            string = string.replace(key, value)

    return string

print(replace_exception_chars('Old, not old'))

输出将是

New, not new

这篇关于为什么 replace() 在我的 Python 函数中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆