The text.txt file contains the text:

Привет, (Дима,Вася,Игорь)! (Как дела?,Как настроение?,Как жизнь?) Пойдешь (завтра,сегодня,на следующей неделе) на тренировку? 

The task: to create a function that accepts this text and returns it back, but choose only one value from the brackets and replace them with brackets. The choice is random. With line breaks. The number of brackets is not known. For example:

 Привет, Вася! Как дела? Пойдешь сегодня на тренировку? 

Tell me how to implement it? So far, nothing better came up with this:

 def random_text( text ): while True: label_find1 = text.find('(') label_find2 = text.find(')') if label_find1 == -1: break tmp_text1 = text[label_find1:label_find2 + 1] tmp_text2 = text[label_find1 + 1:label_find2] tmp_list = tmp_text2.split(',') tmp_var = random.choice(tmp_list) text = text.replace(tmp_text1, tmp_var) return text 

1 answer 1

re.sub option with re.sub :

 import re import random def random_text(text: str) -> str: def _on_sub_process(match) -> str: # "Дима,Вася,Игорь" -> ["Дима", "Вася", "Игорь"] variants = match.group(1).split(',') return random.choice(variants) # В регулярке выполняется замена выражений внутри круглых скобок return re.sub(r'\((.+?)\)', _on_sub_process, text) text = "Привет, (Дима,Вася,Игорь)! (Как дела?,Как настроение?,Как жизнь?) Пойдешь (завтра,сегодня,на следующей неделе) на тренировку?" new_text = random_text(text) print(new_text) # Привет, Игорь! Как настроение? Пойдешь сегодня на тренировку? new_text = random_text(text) print(new_text) # Привет, Дима! Как жизнь? Пойдешь сегодня на тренировку?