Python | Extract Numbers in Brackets in String

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.