Python re.sub remove starting from specific index?

Viewed 43

I'm have a script that takes data and essentially cleans it by removing nominal-only elements. I'm wondering how I can adjust remove='^[0-9.]+$' to start at a specific index, let's say index 4? Right now it sweeps through each index.


    def split_lines(fp, delimiter, remove='^[0-9.]+$'):
        with open(fp, mode="r", encoding="utf-8") as file:
            clean_list = []
            for line in file:
                tokens = line.split(delimiter)
                tokens = [re.sub(remove, "", token) for token in tokens]
                clean_list.append(list(filter(lambda e: e.strip(), tokens)))
            txt_edit.delete("1.0", tk.END)
            unique_data = {}
            for item in clean_list:
                key = str(item)
                if not unique_data.get(key):
                    unique_data[key] = 1, item
                else:
                    unique_data[key] = (unique_data[key][0] + 1), item
            for k, v in unique_data.items():
                txt_edit.insert(tk.END, f"{v[1]}x {v[0]} \n")
1 Answers

The simplest way might be to only run the clean on part of the string:

my_string = "wowMuchCool"
part_1, part2 = my_string[:4], mystring[4:] # split at the 4th char, so "wowM" and "uchCool"
part_2 = clean_function(part_2) # Let's say it removes "o" here, part_2 = "uchCl"
my_string_cleaned = part_1 + part_2 # "wowMuchCl", the first "o" is untouched
Related