温馨提示×

string怎么替换指定位置字符串

小亿
194
2024-01-16 23:18:44
栏目: 编程语言

要替换指定位置的字符串,可以使用字符串的切片和拼接操作。以下是一个示例代码:

def replace_string_at_index(input_str, replace_str, start_index):
    return input_str[:start_index] + replace_str + input_str[start_index + len(replace_str):]

# 示例用法
input_str = "Hello, World!"
replace_str = "Python"
start_index = 7

new_str = replace_string_at_index(input_str, replace_str, start_index)
print(new_str)

运行结果:

Hello, Python!

在示例代码中,replace_string_at_index函数接受三个参数:input_str表示原始字符串,replace_str表示要替换的字符串,start_index表示要替换的位置索引。函数通过切片操作将原始字符串切成三部分,并拼接起来,其中第一部分是从开头到要替换位置的字符串,第二部分是要替换的字符串,第三部分是从要替换位置加上要替换字符串长度到结尾的字符串。最后返回拼接后的新字符串。

0