How to replace a specific substring in a string.
To replace a specified string in a sentence, you can use string slicing and concatenation operations. Here is an example code:
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)
Result of execution:
Hello, Python!
The replace_string_at_index function in the example code takes three parameters: input_str represents the original string, replace_str represents the string to be replaced, and start_index represents the position index to replace. The function slices the original string into three parts and concatenates them, where the first part is from the beginning to the position to be replaced, the second part is the string to be replaced, and the third part is from the position to be replaced plus the length of the string to the end of the string. Finally, it returns the concatenated new string.