I'd use a regexp:

>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']

This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b:

>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']

To end up with a list of numbers instead of a list of strings:

>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]

NOTE: this does not work for negative integers

Answer from Vincent Savard on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-extract-numbers-from-string
Python | Extract Numbers from String - GeeksforGeeks
November 10, 2025 - re.findall(r'-?\d*\.?\d+', s): extracts all positive, negative, and decimal numbers from the string.
Discussions

Is there a better way to extract numbers from a string in python 3 - Stack Overflow
I have strings of the form "V70N-HN" and I just need to get the 70 out. The first characters can be any number of letters, or none at all. Same goes for the final characters. I've used More on stackoverflow.com
🌐 stackoverflow.com
python 3.x - Extract a number after a particular string - Software Engineering Stack Exchange
I have a string series[Episode 37]-03th_July_2010-YouTube and I want to extract the number which comes directly after Episode (eg: 37 from Episode 37)the position ofEpisode 37` may not be fixed in ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
October 17, 2016
How to extracts number from this python list
This has two loops; one to examine each character and extract only the digits, and a second one to iterate over my_list: >>> my_list = [ ' 14,200 new items ' , '15,200 new items '] >>> [char for char in my_list[0] if char.isdigit()] ['1', '4', '2', '0', '0'] >>> "".join([char for char in my_list[0] if char.isdigit()]) '14200' >>> int("".join([char for char in my_list[0] if char.isdigit()])) 14200 >>> def extract_int(istr): return int("".join([char for char in istr if char.isdigit()])) ... >>> extract_int(my_list[0]) 14200 >>> [extract_int(phrase) for phrase in my_list] [14200, 15200] >>> More on reddit.com
🌐 r/learnpython
29
18
June 25, 2022
Extract Numbers from Within Strings in Pandas Column
I’m guessing it’s doable with Regex, but that’s a complete black art to me. More on reddit.com
🌐 r/learnpython
5
2
May 21, 2021
🌐
Medium
beckmoulton.medium.com › practical-skills-for-extracting-string-numbers-in-python-12a8bf5957d0
Practical skills for extracting string numbers in Python | by Beck Moulton | Medium
November 14, 2024 - import re #Define a string containing ... example,re.findall()Method: Use regular expressions\d+Match one or more consecutive numbers.re.findall()Return a list containing all the matching numbers in the string....
Top answer
1 of 2
6

Regular expressions to the rescue!

I see you are already on the right path, by using a regular expression. But you could try using a regular expression with a capture in order to capture the digits following the string "Episode".

Here is a small example to get you going:

import re
m = re.search('Episode (\d+)', 'series[Episode 37]-03th_July_2010-YouTube', re.IGNORECASE)
m.group(1)

The last statement, m.group(1), returns the contents of the first group (what's inside the parentheses in the regular expression). In this case it will be the string '37', which is the digits that follows the string "Episode ".

Also notice I'm using the IGNORECASE flag, so this will work regardless of the casing of the string "Episode". So "episode" and even "ePISODE" will work too.

2 of 2
1

Kind of broad, pulling from a text file, but will do for many applications of getting both integers and floats out of strings.

The file, commaseperated.txt has a row looking like this:

Input: (0, 1, 2.4), 1, 5, 8, 99.7, 0.1), (, )()!@!#, 9
    import re


    # a function to pull the numbers from many lists of strings
    def func(a, z, c):
        # -- Read .txt -- #
        filename = 'commaseperated.txt'
        f1 = open(filename, 'r')  # open the file for reading
        data = f1.readlines()  # read the entire file as a list of strings
        f1.close()
        #
        for line in data:
            cells = line.strip().split(',')
            # empty string
            b = ""
            # range through cells of from a text file split by commas
            for i in range(a, len(cells[z:c])+a):
                # no commas in the cells so make dummy commas for new string
                b += cells[i] + ','
            # find all the numbers
            z = re.findall(r'\d+(?:\.\d+)?', b)
            # return a list of floated values from the text string
            return [float(z[s]) for s in range(len(z))]
    Output: [0, 1, 2.4, 1, 5, 8, 99.7, 0.1, 9]
Find elsewhere
🌐
Esri Community
community.esri.com › t5 › python-questions › extracting-an-integer-from-a-string-field › td-p › 180857
Extracting an integer from a string field - Esri Community
April 21, 2017 - 1. Right click on your new field, to get to the field calculator 2. Click the Python radio button 3. Check the Show Codeblock box 4. In the Pre-Logic Script Code box, copy and paste this function: def get_num_from_string(string): '''This function retrieves numbers from a string and converts ...
🌐
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 “2” (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.
🌐
Facebook
facebook.com › groups › python › posts › 1005793050261259
What's the best way to extract a number from a string?
Popular groups · Find communities for you · Over 1 billion people across the globe are using Facebook Groups to explore their favorite topics · Log in · Categories · Science & tech · Travel · Animals · Sports & fitness · Entertainment
🌐
TecHighness
techighness.com › home › how to extract numbers from a string in python
How to Extract Numbers From a String in Python - TecHighness
April 14, 2025 - You can use extract-numbers library to extract numbers from text in your Python code.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python extract numbers from string
Python Extract Numbers From String - Spark By {Examples}
May 21, 2024 - How to extract numbers from a string in Python? To extract numbers(both integers and floating-point numbers) from a string in Python, you can use regular
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-extract-numbers-from-a-string-in-python
How to extract numbers from a string in Python?
March 24, 2026 - Whether you need integers, floating-point numbers, or both, these techniques will help you parse numeric data from text efficiently. The most powerful approach uses regular expressions to match different number patterns ? import re # Extract integers and floats text = "The price is $29.99 and quantity is 5" numbers = re.findall(r'\d+\.\d+|\d+', text) print("String format:", numbers) # Convert to appropriate numeric types numeric_values = [] for num in numbers: if '.' in num: numeric_values.append(float(num)) else: numeric_values.append(int(num)) print("Numeric format:", numeric_values)
🌐
Medium
akshatsoni64.medium.com › extract-numbers-from-a-string-python-6c851e10aa87
Extract Numbers from a String — Python | by Akshat Soni | Medium
January 26, 2021 - # Note: We only have to extract complete numbers, Float numbers will be considered as 2 different complete numbersstring = "I will eat 2 burgers 2345 fries & 1.25 cokes l8r9 aa" numbers = [] for val in string.split(" "): if str.isdigit(val): numbers.append(val) else: # Check for Float Numbers if '.' in val: for digit in val.split('.'): if str.isdigit(digit): numbers.append(digit) # Non Float Values else: add = 0 # Check every character inside string for i in range(len(val)): # Consecutive Numbers if ord(val[i]) in range(48, 58): if add > 0: add = (add*10) + int(val[i]) # Numbers mixed with character [a2bc3] else: add += int(val[i]) if i == len(val)-1: numbers.append(add) else: if add > 0: numbers.append(add) add = 0print(len(numbers)) print(numbers)
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations
Python does not currently have ... more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions. To extract the filename and numbers from a string like...
🌐
Data Science Parichay
datascienceparichay.com › home › blog › extract numbers from string in python
Extract Numbers From String in Python - Data Science Parichay
January 3, 2022 - You can iterate through the string and use the string isdigit() function to extract numbers from a string in Python.
🌐
Jina AI
jina.ai › reader
Reader API - Jina AI
Remove these elements before extraction. Example: nav, footer, .sidebar, #ads ... Strip all images from the output.
🌐
Towards AI
pub.towardsai.net › i-tested-gpt-5-4-vs-claude-opus-4-6-on-20-real-tasks-the-1-model-on-lmsys-isnt-what-you-think-8ade957dea0d
I Tested GPT-5.4 vs Claude Opus 4.6 on 20 Real Tasks — The #1 Model on LMSYS Isn't What You Think | by Chew Loong Nian - AI ENGINEER | Towards AI
April 8, 2026 - I Tested GPT-5.4 vs Claude Opus 4.6 on 20 Real Tasks — The #1 Model on LMSYS Isn't What You Think Two days ago, Claude Opus 4.6 quietly took the #1 spot on the LMSYS Chatbot Arena with an Elo score …
🌐
scikit-learn
scikit-learn.org › stable › modules › model_evaluation.html
3.4. Metrics and scoring: quantifying the quality of predictions — scikit-learn 1.9.0 documentation
For the most common use cases, you can designate a scorer object with the scoring parameter via a string name; the table below shows all possible values. All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as ‘neg_mean_squared_error’ which return the negated value of the metric. ... >>> from sklearn import svm, datasets >>> from sklearn.model_selection import cross_val_score >>> X, y = datasets.load_iris(return_X_y=True) >>> clf = svm.SVC(random_state=0) >>> cross_val_score(clf, X, y, cv=5, scoring='recall_macro') array([0.96, 0.96, 0.96, 0.93, 1.
🌐
pavelslepenkov.info
0x4ad.com › posts › extract-numbers-from-string-in-python
Extract numbers from string in python with real life example
Start with replacing chars which can be clumped with our number, then split string to list, go through each element of the list and try to convert these parts to a numbers - int or float.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-splitting-text-and-number-in-string
Python - Splitting Text and Number in string - GeeksforGeeks
July 12, 2025 - Python · from itertools import groupby # Initializing the input string a = "abc123" # Splitting the string using groupby groups = ["".join(g) for k, g in groupby(a, key=str.isdigit)] # Grouping by type s = groups[0] # Extracting text n = groups[1] # Extracting numbers print(s, n) Output ·