Python | Extract Numbers in Brackets in String
Last Updated :
09 Apr, 2023
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))
OutputThe 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))
OutputThe 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)
Method 4: Using split() and isdigit() methods
Step-by-step approach:
- Initialize a list variable to store the extracted numbers.
- Split the string using the "[" and "]" characters as delimiters. This will create a list of substrings.
- Loop through the substrings and check if each substring contains a number using the isdigit() method.
- If a substring contains a number, append it to the list variable.
- Print the list of extracted numbers.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Extract Numbers in Brackets in String
# Using split() and isdigit() methods
# 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 split() and isdigit() methods
num_list = []
for substring in test_str.split("["):
if "]" in substring:
num = substring.split("]")[0]
if num.isdigit():
num_list.append(int(num))
# printing result
print("Extracted number list : " + str(num_list))
OutputThe 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 input string. This is because we need to loop through each character in the string once.
Auxiliary space: O(m), where m is the number of numbers in brackets in the input string. This is because we need to store each extracted number in a list.
Method 6: Using a loop and string manipulation
Step-by-step approach:
- Initialize two variables, start and end, to track the indices of the brackets enclosing the number.
- Loop through each character of the string.
- If a bracket is encountered, check whether it is an opening or closing bracket.
- If it is an opening bracket, set the start index to the current index.
- If it is a closing bracket, set the end index to the current index and extract the substring between the start and end indices.
- Check whether the extracted substring contains only digits.
- If it does, append the substring to the list of extracted numbers.
- Return the list of extracted numbers.
Below is the implementation of the above approach:
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
res=[]
start = -1
end = -1
for i in range(len(test_str)):
if test_str[i] == "[":
start = i
elif test_str[i] == "]":
end = i
num_str = test_str[start+1:end]
if num_str.isdigit():
res.append(num_str)
# printing result
print("Extracted number list : " + str(res))
OutputThe original string is : gfg is [1] [4] all geeks
Extracted number list : ['1', '4']
Time complexity: O(n)
Auxiliary space: O(1)
Method 6: Using list comprehension and isdigit() method
- Split the string on spaces to get a list of words.
- Use list comprehension to iterate through the list of words and extract the numbers that are enclosed in square brackets using the isdigit() method.
- Return the list of extracted numbers.
Python3
# Python3 code to demonstrate working of
# Extract Numbers in Brackets in String
# Using list comprehension and isdigit() method
# 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 list comprehension and isdigit() method
res = [int(word.strip("[]")) for word in test_str.split() if word.startswith("[") and word.endswith("]") and word.strip("[]").isdigit()]
# printing result
print("Extracted number list : " + str(res))
OutputThe 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 string.
Auxiliary space: O(n), where n is the length of the string.
Similar Reads
Python - Extract numbers from list of strings
We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = ['apple 123', 'banana 456', 'cherry 789'] we need to extract numbers from the string in list so that output becomes [123, 456, 789].Using Regular ExpressionsThis method us
2 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Python - Extract date in String
Given a string, the task is to write a Python program to extract date from it. Input : test_str = "gfg at 2021-01-04" Output : 2021-01-04 Explanation : Date format string found. Input : test_str = "2021-01-04 for gfg" Output : 2021-01-04 Explanation : Date format string found. Method #1 : Using re.s
4 min read
Python Check If String is Number
In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number.Example: Using isdigit() MethodPython# Python code to check if string is numeric
6 min read
Frequency of Numbers in String - Python
We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6).Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match sp
3 min read
Python - Check if String contains any Number
We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Extract substrings between brackets - Python
Extract substrings between bracket means identifying and retrieving portions of text that are enclosed within brackets. This can apply to different types of brackets like (), {}, [] or <>, depending on the context.Using regular expressions Regular expressions are the most efficient way to extr
3 min read
Python | Convert Joint Float string to Numbers
Sometimes, while working with Legacy languages, we can have certain problems. One such can be working with FORTRAN which can give text output (without spaces, which are required) '12.4567.23' . In this, there are actually two floating point separate numbers but concatenated. We can have problem in w
5 min read
Python - Extract String till Numeric
Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
5 min read
Separate Alphabets and Numbers in a String - Python
The task is to separate alphabets and numbers from a string. For example, given "a1b2c3", the output should be alphabets "abc" and numbers "123".Using List ComprehensionList comprehension offers a concise and efficient way to separate alphabets and numbers from a string. It iterates through each cha
2 min read