为什么replace()在我的Python函数中不起作用?

时间:2019-05-20 10:22:33

标签: python python-3.x 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.replace(exception_char, exception_chars_dict[exception_char])
    return string

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

如果我尝试运行它,则会在OUTPUT中获得不变的源字符串。请看一看: enter image description here

为什么会这样?

更新 所需的输出:

  

新的,不是新的

6 个答案:

答案 0 :(得分:3)

replace()不能就地工作:

  

方法replace()返回字符串的副本,在该字符串中,已用新的替换了旧的出现,可以选择将替换次数限制为最大。

所以您错过了作业:

string = string.replace(exception_char, exception_chars_dict[exception_char])

答案 1 :(得分:1)

函数str.replace()不会更改您调用它的字符串-不能,字符串是不可变的-它返回新的字符串。您不会将输出保存到变量中,因此会丢失。

您需要将string.replace(exception_char, exception_chars_dict[exception_char])交换为string = string.replace(exception_char, exception_chars_dict[exception_char])

答案 2 :(得分:1)

您只是原谅将值保存在循环中。 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

答案 3 :(得分:1)

尝试一下

 string.replace(exception_char, exception_chars_dict[exception_char])

更改为

string = string.replace(exception_char, exception_chars_dict[exception_char])

答案 4 :(得分:1)

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

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

  

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

如果您一起迭代键和值,那么您的逻辑也可以像下面这样简化

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

答案 5 :(得分:0)

您需要存储要存储的值。 因此,而不是

string.replace(exception_char, exception_chars_dict[exception_char])

string = string.replace(exception_char, exception_chars_dict[exception_char])

完整代码

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'))