I have a list with each item being a string. I want to do a search and replace in this list, but the replace may happen across multiple items. The replaced string goes to the first item and subequent items becomes blank. It's easier to explain with examples (not an exhaustive list of variations).
str_list = ["abc", "de", "fg", "hij", "abcde", "klm"]
def replace_parts(input_list, find_str, replace_str):
"""Function which will do the trick"""
...
# case1
replace_parts(str_list, "ab", "xy")
print(str_list)
# ["xyc", "de", "fg", "hij", "xycde", "klm"]
# case2
replace_parts(str_list, "abcd", "xy")
print(str_list)
# ["xy", "e", "fg", "hij", "xye", "klm"]
# case3
replace_parts(str_list, "cdef", "xyz")
print(str_list)
# ["abxyz", "", "g", "hij", "abcde", "klm"]
I'd like to know if there are any libraries which can do this. or if there is a pythonic way of solving this problem.
Actually I am dealing with objects in python pptx
module with paragraph
and runs
. Here's the code that I have come up with now. But it's still a bit buggy and I don't know if this is the right way to solve the whole problem.
def para_text_replace(para, find_string, replace_string):
find_string = str(find_string)
replace_string = str(replace_string)
starting_pos = para.text.find(find_string)
if starting_pos == -1:
return # text not in paragraph
txt_prev = ""
for run in para.runs:
if len(txt_prev) <= starting_pos < len(txt_prev) + len(run.text):
if run.text.find(find_string) != -1:
run.text = run.text.replace(find_string, replace_string)
return
else:
txt_prev = txt_prev + run.text
run.text = run.text[:starting_pos - len(txt_prev)] + replace_string
elif starting_pos < len(txt_prev) and starting_pos + len(find_string) >= len(txt_prev) + len(run.text):
txt_prev = txt_prev + run.text
run.text = ""
elif len(txt_prev) < starting_pos + len(find_string) < len(txt_prev) + len(run.text):
txt_prev = txt_prev + run.text
run.text = run.text[starting_pos + len(find_string) - len(txt_prev):]
else:
txt_prev += run.text