>>> import re
>>> I = "I=2.7A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.7'
>>> I = "A=3V"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'3'
>>> I = "I=2.723A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.723'
Answer from Nolen Royalty on Stack Overflow
๐ŸŒ
GitHub
gist.github.com โ€บ tbarron โ€บ 3c452da7b5b36de47a05f254484ab83f
python module to extract numbers from text ยท GitHub
python module to extract numbers from text ยท Raw ยท numberize.py ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Discussions

word2num: Convert complex "word numbers" to numerical values
Imma test it with how older people day numbers like 2000 (twenty one hundred) More on reddit.com
๐ŸŒ r/Python
11
28
May 11, 2023
Python-DOCX and extract numbered items from word document - Stack Overflow
I am trying to extract all headings in a Word docx document that are part of a numbered list. The numbered list has been formatted by Word such that when you press return it adds the next number. I... More on stackoverflow.com
๐ŸŒ stackoverflow.com
regex - How to extract particular numbers by matching a word using python regular expression? - Stack Overflow
I want to extract the version numbers using python regular expression. ... Copyshow.sh { "sys_0_num" : { "rel_num": 2.3, "version": 14891 }, "sys_1_num" : { "rel_num": 2.3, "version": 14891 } "cha_num" : { "rel_num": 2.3, "version": 571, "model":1487 } } I want to extract the version number from ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Extract digits from a string within a word - Stack Overflow
I want a regular expression, which returns only digits, which are within a word, but I can only find expressions, which returns all digits in a string. I've used this example: text = 'I need this n... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python extract numbers from string
Python Extract Numbers From String - Spark By {Examples}
May 21, 2024 - # Quick examples of extracting numbers from a string import re import numpy as np # Initialize the string string = "Hello, my age is 29 years and 140 days" # Example 1: Using list comprehension and isdigit() method numbers = [int(word) for word ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-extract-numbers-from-a-string-in-Python
How to extract numbers from a string in Python?
August 10, 2023 - text = "There are 10 apples and 25 oranges" numbers = [] for word in text.split(): if word.isdigit(): numbers.append(int(word)) print("Extracted numbers:", numbers)
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ string โ€บ extract-digits-from-python-string
2 Easy Ways to Extract Digits from a Python String - AskPython
May 5, 2026 - inp_str = "Order-1034-spent-500" number = int("".join(char for char in inp_str if char.isdigit())) print(number) print(type(number)) ... One thing to watch: isdigit() returns True for Unicode digit characters like the fullwidth digit โ€œ๏ผ’โ€ (U+FF12) in addition to plain ASCII digits. If you are processing user input or data from external sources, this may or may not be what you want. For ASCII-only digits, you can check '0' <= char <= '9' instead. Pythonโ€™s regular expression module handles digit extraction with the pattern \d+, which matches one or more consecutive digit characters.
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ word2num: convert complex "word numbers" to numerical values
r/Python on Reddit: word2num: Convert complex "word numbers" to numerical values
May 11, 2023 -

Hey all, I just published my first Python package called word2num. It converts written numbers like "one hundred and twenty-five" or "nine and three quarters" to their numerical values. There are a handful of other packages out there that do this already, but they're mostly no longer maintained and do not support fractional values (the key feature I need for my project).

It supports a variety of types of numbers and uses configurable fuzzy string matching to account for typos. It only supports English at the moment, but contributions for other languages would be more than welcome.

If you want to give it a try, you can pip install word2num.

from word2num import word2num
word2num("twenty nine and a half") # 29.5

Check out the GitHub repo for more usage info and examples. My experience in Python is quite limited, so if anything comes across as non-Pythonic, I'd appreciate a heads-up! ๐Ÿ™Œ

Find elsewhere
๐ŸŒ
My Tec Bits
mytecbits.com โ€บ home โ€บ internet & web dev. โ€บ python โ€บ how to extract numbers from string in python?
How to extract numbers from string in Python? | My Tec Bits
August 9, 2019 - This method can extract integers, float and negative numbers and convert them to float. Here is a code sample. # Assogn a long string to a variable some_string = "Some paragraph with 2 to 5 numbers and some float \ and nagetive numbers like -23 or 32.5 to test the split \ option in Python version 3.7" # Logic to get the numbers in a list numbers = [] for word in some_string.split(): try: numbers.append(float(word)) except ValueError: pass print(numbers)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-extract-digits-from-given-string
Python - Extract digits from given string - GeeksforGeeks
January 28, 2025 - For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Python methods like using regular expressions and basic string manipulation to get only the numbers from a string.
๐ŸŒ
Python Guides
pythonguides.com โ€บ extract-numbers-from-a-string-in-python
How To Extract Numbers From A String In Python?
March 19, 2025 - Another way to extract numbers from a string is by using a combination of list comprehension and the isdigit() method in Python. Hereโ€™s an example: text = "Liam Olivia Noah Emma Oliver Charlotte Elijah Amelia William Sophia James Isabella Benjamin Mia Lucas Ava Henry Evelyn Alexander Harper" ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-find-number-in-string
How to Find Numbers in a String Using Python
November 4, 2025 - From the output, you can see that the filter() method with isdigit() and join() method extracts the number from the string. The isdigit() method also checks whether the current character is a digit. So, using this, you can iterate over each string character and then check whether it is a digit.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 54702433 โ€บ python-docx-and-extract-numbered-items-from-word-document
Python-DOCX and extract numbered items from word document - Stack Overflow
I am trying to extract all headings in a Word docx document that are part of a numbered list. The numbered list has been formatted by Word such that when you press return it adds the next number. I...
๐ŸŒ
YouTube
youtube.com โ€บ watch
How To Extract Numbers From A Text File In Python: Beginners Mini Project 2024 - YouTube
Python Project Extracting Digits From A .txt File. Beginners Easy To Follow Code Example Using Regex.#pythonbeginners #pythonproject
Published ย  May 29, 2024
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-get-integer-values-from-a-string-in-python
How to get integer values from a string in Python?
March 24, 2026 - text = "There are 21 oranges, 13 apples and 18 bananas in the basket" print("The given string is:") print(text) # Split string and filter digits numbers = [] for word in text.split(): # Remove punctuation and check if remaining is digit clean_word = ''.join(char for char in word if char.isdigit()) if clean_word: numbers.append(int(clean_word)) print("The numbers present in the string are:") print(numbers) The given string is: There are 21 oranges, 13 apples and 18 bananas in the basket The numbers present in the string are: [21, 13, 18] Use regular expressions for the most flexible integer extraction from strings.
Top answer
1 of 2
1

You can use

re.findall(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', text)

This regex will extract all one or more digit chunks that are immediately preceded or followed with an ASCII letter.

A fully Unicode version for Python re would look like

(?<=[^\W\d_])\d+|\d+(?=[^\W\d_])

where [^\W\d_] matches any Unicode letter.

See the regex demo for reference.

2 of 2
-1

An approach with str.translate, without the use of regex or re module:

from string import ascii_letters

delete_dict = {sp_character: '' for sp_character in ascii_letters}
table = str.maketrans(delete_dict)

text = 'I 77! need 1:5 this number inside my wor5d, but also this word3 and this 4word, but not this 1 and not this 555.'

print([res for s in text.rstrip('.').split()
       if not (s2 := s.rstrip(',')).isnumeric() and (res := s2.translate(table)) and res.isnumeric()])

Out:

['5', '3', '4']

Performance

I was curious so I did some benchmark tests to compare performance against other approaches. Looks like str.translate is faster even than the regex implementation.

Here is my benchmark code with timeit:

import re
from string import ascii_letters
from timeit import timeit


_NUM_RE = re.compile(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])')

delete_dict = {sp_character: '' for sp_character in ascii_letters}
_TABLE = str.maketrans(delete_dict)

text = 'I need this number inside my wor5d, but also this word3 and this 4word, but not this 1 and not this 555.'


def main():
    n = 100_000

    print('regex:         ', timeit("re.findall(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', text)",
                 globals=globals(), number=n))

    print('regex (opt):   ', (timeit("_NUM_RE.findall(text)",
                 globals=globals(), number=n)))

    print('iter_char:     ', timeit("""
k=set()
for x in range(1,len(text)-1):
    if text[x-1].isdigit() and text[x].isalpha():
        k.add(text[x-1])
    if text[x].isdigit() and text[x+1].isalpha():
        k.add(text[x])
    if text[x-1].isalpha() and text[x].isdigit() and text[x+1].isalpha():
        k.add(text[x])
    if text[x-1].isalpha() and text[x].isdigit():
        k.add(text[x])
    """, globals=globals(), number=n))

    print('str.translate: ', timeit("""
[
    res for s in text.rstrip('.').split()
    if not (s2 := s.rstrip(',')).isnumeric() and (res := s2.translate(_TABLE)) and res.isnumeric()
]
    """, globals=globals(), number=n))


if __name__ == '__main__':
    main()

Results (Mac OS X - M1):

regex:          0.5315765410050517
regex (opt):    0.5069837079936406
iter_char:      2.5037198749923846
str.translate:  0.37348733299586456
๐ŸŒ
YouTube
youtube.com โ€บ the python oracle
How to extract numbers from a string in Python? - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Mysterio...
Published ย  February 4, 2023
Views ย  70
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-extract-numbers-from-string
Python | Extract Numbers from String - GeeksforGeeks
September 16, 2024 - 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 construc ยท 6 min read Python - Extract Rear K digits from Numbers