How to remove text inside brackets in Python?
Last Updated :
18 Feb, 2023
In this article, we will learn how to remove content inside brackets without removing brackets in python.
Examples:
Input: (hai)geeks
Output: ()geeks
Input: (geeks)for(geeks)
Output: ()for()
We can remove content inside brackets without removing brackets in 2 methods, one of them is to use the inbuilt methods from the re library and the second method is to implement this functionality by iterating the string using a for loop
Method 1: We will use sub() method of re library (regular expressions).
sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string.
This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets.
Approach :
- Import the re library
- Now find the sub-string present in the brackets and replace with () using sub() method.
- We need to pass the sub() method with 2 arguments those are pattern and string to be replaced with.
- Print the string.
In the below code \(.*?\) represents the regular expression for finding the brackets containing some content. The brackets () have some special meaning in regular expression in python so Backlash \ is used to escape that meaning.
Python3
import re
string = "(Geeks)for(Geeks)"
string = re.sub( "\(.*?\)" , "()" ,string)
print (string)
|
Time complexity: O(2^m + n), Where m is the size of the regex, and n is the size of the string. Here the sub() method will take 2^m time to find the pattern using the regex and O(n) to iterate through the string and replace with the “()”.
Auxiliary space: O(1), because this operation does not consume any additional memory, but just modifies the input string in place.
Method 2: In this method, we will iterate through the string and if the character that is being iterated is not present in between the parenthesis then the character will be added to the resultant string.
If there is an open or closed parenthesis present in the string then the parenthesis will be added to the resultant string but the string in between them is not added to the resultant string.
Approach:
- Iterate the loop for each character in the string.
- If a ‘(‘ or ‘)’ appears in the string we will add it to the result string.
- If the parenthesis number in the string is zero then add the character to the result string.
- Here if the parenthesis number is greater than zero it indicates that the current character which is being iterated is present in between two parentheses
- Print the result string.
Python3
string = "geeks(for)geeks"
result = ''
paren = 0
for ch in string:
if ch = = '(' :
paren = paren + 1
result = result + '('
elif (ch = = ')' ) and paren:
result = result + ')'
paren = paren - 1
elif not paren:
result + = ch
print (result)
|
Time complexity : O(n), Here n is the length of the string. In the code, we are iterating through the string and appending the content outside of the parenthesis so it would only take the time O(n).
Auxiliary space: O(n), as the resultant string can be of the same length as the input string in the worst case.
Method 3 : Using replace(),split() and join() methods
Python3
string = "(Geeks)for(Geeks)"
x = string
x = x.replace( "(" , "*(" )
x = x.replace( ")" , ")*" )
y = x.split( "*" )
res = []
for i in y:
if len (i)! = 0 :
if i[ 0 ] = = "(" and i[ - 1 ] = = ")" :
res.append( "()" )
else :
res.append(i)
res = "".join(res)
print (res)
|
Time Complexity : O(N)
Auxiliary Space : O(N)
Similar Reads
How to remove brackets from text file in Python ?
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. Syntax: # import re module for using regular expression import re patn = re.sub(pattern, repl, senten
3 min read
How to remove text from a label in Python?
Prerequisite: Python GUI â tkinter In this article, the Task is to remove the text from label, once text is initialized in Tkinter. Python offers multiple options for developing GUI (Graphical User Interface) out of which Tkinter is the most preferred means. It is a standard Python interface to the
1 min read
Python | Remove square brackets from list
Sometimes, while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print the whole list without accessing the elements for loops, we require a method to perform this. Let's discuss a shorthand by which this task can be
5 min read
How to remove blank lines from a .txt file in Python
Many times we face the problem where we need to remove blank lines or empty spaces in lines between our text to make it look more structured, concise, and organized. This article is going to cover two different methods to remove those blank lines from a .txt file using Python code. This is going to
3 min read
How to Remove Item from a List in Python
Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the element or index. The simplest way to remove an element from a list by
3 min read
How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file b
5 min read
How to remove numbers from string in Python - Pandas?
In this article, let's see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files. Syntax: for the method 'replace()': str.replace(
2 min read
How to Remove Letters From a String in Python
Removing letters or specific characters from a string in Python can be done in several ways. But Python strings are immutable, so removal operations cannot be performed in-place. Instead, they require creating a new string, which uses additional memory. Letâs start with a simple method to remove a s
3 min read
How to Remove tags using BeautifulSoup in Python?
Prerequisite- Beautifulsoup module In this article, we are going to draft a python script that removes a tag from the tree and then completely destroys it and its contents. For this, decompose() method is used which comes built into the module. Syntax: Beautifulsoup.Tag.decompose() Tag.decompose() r
2 min read
How to reverse a String in Python
Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works: Using string slicingThis slicing method is one of the
4 min read