Python中可以使用str.replace()方法来实现一键替换。该方法用于将字符串中的指定子字符串替换为另一个子字符串。其语法如下:
new_string = old_string.replace(old_substring, new_substring)
其中,old_string是原始字符串,old_substring是需要替换的子字符串,new_substring是替换后的子字符串。调用replace()方法后,会返回一个新的字符串new_string,其中所有的old_substring都被替换为new_substring。
以下是一个示例:
sentence = "I love apples. Apples are delicious."
new_sentence = sentence.replace("apples", "oranges")
print(new_sentence)
输出结果为:
I love oranges. Oranges are delicious.
在上述示例中,原始字符串sentence中的所有"apples"都被替换为"oranges",并存储在新的字符串new_sentence中。