import typing import re def dedupilicate(value: str, existing_values: typing.Iterable[str]): """ If is present in , returns '(1)'. If '(1)' is present in , returns '(2)' and so on. A typical use would run through this function and then append it to . :param value: str :param existing_values: an iterable of strings :return: str """ reccurances = [] for existing_label in existing_values: if value == existing_label: reccurances.append(1) re_match = re.match(f"{value}\((.*)\)", existing_label) if re_match: current_reccurance = int(re_match.group(1)) reccurances.append(current_reccurance + 1) if len(reccurances) == 0: return value else: return f"{value}({max(reccurances)})"