The Wayback Machine - https://web.archive.org/web/20230108190959/https://www.geeksforgeeks.org/python-extract-numbers-in-brackets-in-string/
Skip to content
Related Articles

Related Articles

Python | Extract Numbers in Brackets in String

Improve Article
Save Article
  • Last Updated : 02 Jan, 2023
Improve Article
Save Article

Sometimes, while working with Python strings, we can have a problem in which we have to perform the task of extracting numbers in strings that are enclosed in brackets. Let’s discuss the certain ways in which this task can be performed. 

Method 1: Using regex The way to solve this task is to construct a regex string that can return all the numbers in a string that has brackets around them. 

Python3




# Python3 code to demonstrate working of
# Extract Numbers in Brackets in String
# Using regex
import re
 
# initializing string
test_str = "gfg is [1] [4] all geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract Numbers in Brackets in String
# Using regex
res = re.findall(r"\[\s*\+?(-?\d+)\s*\]", test_str)
 
# printing result
print("Extracted number list : " + str(res))

Output : 

The original string is : gfg is [1] [4] all geeks
Extracted number list : ['1', '4']

Time Complexity: O(N), where N is the length of the given string.
Space Complexity: O(N)

Method 2 : Using startswith(), endswith() and replace() methods

Initially split the string. Iterate over the list after splitting, check for strings in the list that start with “[” and end with”]”.If found remove those square braces and check whether the string after removing braces is numeric or not.

Python3




# Python3 code to demonstrate working of
# Extract Numbers in Brackets in String
 
# initializing string
test_str = "gfg is [1] [4] all geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract Numbers in Brackets in String
x=test_str.split()
res=[]
for i in x:
    if i.startswith('[') and i.endswith(']') :
        a=i.replace('[','')
        a=a.replace(']','')
        if a.isdigit():
            res.append(a)
# printing result
print("Extracted number list : " + str(res))

Output

The original string is : gfg is [1] [4] all geeks
Extracted number list : ['1', '4']

Time Complexity: O(N), where N is the length of the given string.
Space Complexity: O(N)

Method 3 : Using find() and replace() methods

Python3




# Python3 code to demonstrate working of
# Extract Numbers in Brackets in String
 
# initializing string
test_str = "gfg is [1] [4] all geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract Numbers in Brackets in String
x=test_str.split()
res=[]
for i in x:
    if i.find('[')==0 and i.find(']')==len(i)-1 :
        a=i.replace('[','')
        a=a.replace(']','')
        if a.isdigit():
            res.append(a)
# printing result
print("Extracted number list : " + str(res))

Output

The original string is : gfg is [1] [4] all geeks
Extracted number list : ['1', '4']

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!