-3

The program must remove all parentheses from the text and everything inside the parentheses. When entering "text)" or "text (text)" everything works fine. But there is an error in case I enter "text(". I'm new to Python and I understand that my code is 100% bulky than it should be. Can you please tell me what's wrong with my code?

print("Программа удаляет из текста все круглые скобки "
      "и всё, что было внутри этих скобок.")


# Создал функцию parentheses_text_remove.
# Она делает всю работу, а в конце мы просто вызываем её.
def parentheses_text_remove(text):
    # Цикл, чтобы находило все скобки в тексте.
    while "(" in text:
        # Переменная start, находит открывающую скобку.
        start = text.index("(")
        """
        Следующая строка кода нужна для удаления пробела перед "(".
        Слайсим весь текст до start, т.е. до "(" и ищем последний
        пробел до start.
        """
        start = text[:start].rfind(" ", 0, start)
        # Переменная end находит закрывающую скобку.
        end = text.index(")", start)
        """
        Объединяем всё, что ДО скобок с тем, что ПОСЛЕ.
        Всё, что внутри скобок, включая сами скобки,
        в новом тексте не участвует.
        """
        text = text[:start] + text[end + 1:]
    return text


# Добавил всё в цикл, чтобы имитировать какое-никакое общение.
while True:
    initial_input = input("Для запуска введите «Старт», "
                          "для выхода введите «Выход»."
                          "\n> ").lower().strip()
    if initial_input == "старт":
        while True:
            # Собственно, ввод и вывод текста.
            user_input = input("Введите текст: ")
            final_output = parentheses_text_remove(user_input)
            if user_input == "":
                print("Вы ничего не ввели. Попробуйте заново "
                      "или введите «Выход» для выхода.")
                continue
            elif user_input in ["выход", "Выход", "ВЫХОД"]:
                print("Выход из программы..."
                      "\n...завершён.")
                exit()
            print("Результат:", final_output)
    elif initial_input == "выход":
        print("Выход из программы..."
              "\n...завершён.")
        quit()
    else:
        print("Некорректный ввод. Попробуйте заново.")
        continue

Error when trying to enter "text(":

Traceback (most recent call last):
  File "D:\PycharmProjects\Python\myfile.py", line 38, in <module>
    final_output = parentheses_text_remove(user_input)
  File "D:\PycharmProjects\Python\myfile.py", line 19, in parentheses_text_remove
    end = text.index(")", start)
ValueError: substring not found

How to make the program ignore "text("?

I tried this:

if ")" not in text[start:]:
            text = text[:start] + "(" + text[start+1:]
            continue

But it doesn't work. In this case, If I enter "text(" the program does nothing. There is no error, I still can enter additional text but when I push Enter button nothing happens.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Local man
  • 19
  • 5

1 Answers1

0
def parentheses_text_remove(text):
    # keep removing pairs of '(' and ')' as long as there are any
    while '(' in text and ')' in text:
        for i, character in enumerate(text):
            # step through the characters until you encounter a closing bracket
            if character == ')':
                j = i
                # walk back until you encounter an opening bracket
                while text[j] != '(':
                    j -= 1
                # strip out the part in brackets
                text = text[:j] + text[i+1:]
                break
    return text

print(parentheses_text_remove(
    'Hello (remove this (remove this as well)) World (this needs to go (too))'
))

prints

Hello  World 
Michael Hodel
  • 2,845
  • 1
  • 5
  • 10
  • This doesn't answer the question *"Can you please tell me what's wrong with my code?"* And OP has problem with text with not matching parentheses. – gre_gor May 30 '23 at 16:16
  • Well, there are comments explaining what the code does. Also, title states "How can I remove any text inside parentheses including the parentheses themselves in Python?", and I provided code that does exactly this. – Michael Hodel May 30 '23 at 16:18
  • You need to read more than the title. – gre_gor May 30 '23 at 16:18
  • The code also fails on `")("`. – gre_gor May 30 '23 at 16:34