您可以编写一个 Python 函数,使用字符串的 replace() 方法将一个字符串中出现的子串用另一个子串代替,例如:

def replace_string(original_string, old_substring, new_substring):
    new_string = original_string.replace(old_substring, new_substring)
    return new_string

# 示例用法
original_string = 'Hello World!'
old_substring = 'World'
new_substring = 'Python'
new_string = replace_string(original_string, old_substring, new_substring)
print(new_string)  # 输出:Hello Python!

在这个例子中,我们定义了一个名为 replace_string 的函数,它接受三个参数:original_string(原始字符串),old_substring(要替换的子串)和 new_substring(替换后的子串)。

函数内部使用 replace() 方法将原始字符串中的 old_substring 替换为 new_substring,并将结果赋给 new_string 变量。最后,函数返回替换后的字符串。

在示例用法中,我们将原始字符串 'Hello World!' 中的子串 'World' 替换为 'Python',并将结果打印输出。输出结果为 'Hello Python!'。

Python 字符串替换函数:使用 replace() 方法

原文地址: https://www.cveoy.top/t/topic/mvq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录