Algorithm step by step:
string = "words{hello||hello1}words" start = string.index('{') + 1 end = string.index('}') replace_str = string[start: end] print(replace_str) # hello||hello1 var_replace = replace_str.split('||') print(var_replace) # ['hello', 'hello1'] string = string.replace(replace_str, '') print(string) # words{}words s = True if s: new_string = string.format(var_replace[0]) print(new_string) # wordshellowords else: new_string = string.format(var_replace[1]) print(new_string) # wordshello1words
In the form of a function:
def foo(string: str, s=True) -> str: start, end = string.index('{') + 1, string.index('}') replace_str = string[start: end] var_replace = replace_str.split('||') string = string.replace(replace_str, '') # Можно схитрить, т.к. True -- 1, False -- 0 # return string.format(var_replace[not s]) return string.format(var_replace[0] if s else var_replace[1]) string = "words{hello||hello1}words" print(foo(string, True)) # wordshellowords print(foo(string, False)) # wordshello1words
Option through the regular season:
import re def foo(string: str, s=True) -> str: def _on_match(match): var_replace = match.group()[1:-1].split('||') return var_replace[0] if s else var_replace[1] return re.sub('{.+?}', _on_match, string) string = "words{hello||hello1}words" print(foo(string, True)) # wordshellowords print(foo(string, False)) # wordshello1words