Python has a string.replace() to replace a certain text with another piece of text in a string
I'm wondering whether there is something like string.replace_index() which can replace the substring from a specific index and does not start from the beginning.
For example:
string = "test test test test"
print string.replace('test', 'world', 1) # "world test test test"
#this is the goal
print string.replace_index('test', 'world', 10) # "test test world test"
CodePudding user response:
There is no built-in way to do this. But you can achieve that this way:
s = "test test test test"
print(s[:5] s[:-5].replace('test', 'world', 1))
Output:
test world test test
CodePudding user response:
Hey this function lets you replace from an index like so
def replace_index(string, index, old_str, new_str, count):
return string[:index] string[index:].replace(old_str, new_str, count)
For Example:
string = "test test test test"
replace_index(string, 10, "test", "world", 1) # "test test world test"
