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.
# 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)) |
The original string is : gfg is [1] [4] all geeks Extracted number list : ['1', '4']
Recommended Posts:
- Python | Extract substrings between brackets
- Python | Extract numbers from string
- Extract numbers from a text file and add them using Python
- Python | Extract numbers from list of strings
- Python | Extract only characters from given string
- Python | Extract words from given string
- Python | Extract digits from given string
- Python | Extract characters except of K string
- Python | Extract odd length words in String
- Python | Extract Score list of String
- Python Regex to extract maximum numeric value from a string
- Python | Extract length of longest string in list
- Python | Remove square brackets from list
- numpy.extract() in Python
- Python | Extract suffix after K
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.

