Assuming:

  • You know there is a comma in the string, so you don't have to search the entire string to find out if there is or not.
  • You know the pattern is 'many_not_digits,few_digits' so there is a big imbalance between the size of the left/right parts either side of the comma.
  • You can get to the end of the string without walking it, which you can in Python because string indexing is constant time

Then you could start from the end and walk backwards looking for the comma, which would be less overall work for your examples than walking from the left looking for the comma.

Doing work in Python code is way slower than using Python engine code written in C, right? So would it really be faster?

  1. Make a string "aaaaa....,12"
  2. use the timeit module to compare each approach - split, or right-walk.
  3. Timeit does a million runs of some code.
  4. Extend the length of "aaaaaaaaaaaaaaaa....,12" to make it extreme.

How do they compare?

  • String split: 1400 "a"'s run a million times took 1 second.
  • String split: 4000 "a"'s run a million times took 2 seconds.
  • Right walk: 1400 "a"'s run a million times took 0.4 seconds.
  • Right walk: 999,999 "a"'s run a million times took ... 0.4 seconds.

!

from timeit import timeit

_split = """num = x.split(',')[-1]"""

_rwalk = """
i=-1
while x[i] != ',':
    i-=1
num = x[i+1:]
"""

print(timeit(_split, setup='x="a"*1400 + ",12"'))
print(timeit(_rwalk, setup='x="a"*999999 + ",12"'))

e.g.

1.0063155219977489     # "aaa...,12" for 1400 chars, string split
0.4027107510046335     # "aaa...,12" for 999999 chars, rwalked. Faster.

Try it online at repl.it

I don't think this is algorithmically better than O(n), but with the constraints of the assumptions I made you have more knowledge than str.split() has, and can leverage that to skip walking most of the string and beat it in practise - and the longer the text part, and shorter the digit part, the more you benefit.

Answer from TessellatingHeckler on Stack Overflow
Top answer
1 of 5
2

Assuming:

  • You know there is a comma in the string, so you don't have to search the entire string to find out if there is or not.
  • You know the pattern is 'many_not_digits,few_digits' so there is a big imbalance between the size of the left/right parts either side of the comma.
  • You can get to the end of the string without walking it, which you can in Python because string indexing is constant time

Then you could start from the end and walk backwards looking for the comma, which would be less overall work for your examples than walking from the left looking for the comma.

Doing work in Python code is way slower than using Python engine code written in C, right? So would it really be faster?

  1. Make a string "aaaaa....,12"
  2. use the timeit module to compare each approach - split, or right-walk.
  3. Timeit does a million runs of some code.
  4. Extend the length of "aaaaaaaaaaaaaaaa....,12" to make it extreme.

How do they compare?

  • String split: 1400 "a"'s run a million times took 1 second.
  • String split: 4000 "a"'s run a million times took 2 seconds.
  • Right walk: 1400 "a"'s run a million times took 0.4 seconds.
  • Right walk: 999,999 "a"'s run a million times took ... 0.4 seconds.

!

from timeit import timeit

_split = """num = x.split(',')[-1]"""

_rwalk = """
i=-1
while x[i] != ',':
    i-=1
num = x[i+1:]
"""

print(timeit(_split, setup='x="a"*1400 + ",12"'))
print(timeit(_rwalk, setup='x="a"*999999 + ",12"'))

e.g.

1.0063155219977489     # "aaa...,12" for 1400 chars, string split
0.4027107510046335     # "aaa...,12" for 999999 chars, rwalked. Faster.

Try it online at repl.it

I don't think this is algorithmically better than O(n), but with the constraints of the assumptions I made you have more knowledge than str.split() has, and can leverage that to skip walking most of the string and beat it in practise - and the longer the text part, and shorter the digit part, the more you benefit.

2 of 5
2

If you are worried about using split from the left because of lots of unwanted characters in the beginning, use rsplit.

s = "abcdef,12"
s.rsplit(",", 1)[-1]

Here, rsplit will start splitting the string from the right and the optional second argument we used will stop rsplit to proceed further than the first comma operator it encountered.

(eg):
s = "abc,def,12"
s.rsplit(",", 1)[-1]
# Outputs 12
s = "abcdef12"
s.rsplit(",", 1)[-1]
# Outputs abcdef12

This will be lot simpler and cleaner to get the string of numbers in the end rather than doing anything manually.

Not to mention, it will be lot easier if we wish to check whether we get only numbers with this. Even if it is a list of strings.

def get_numbers(string_list, skip_on_error=True):
    numbers_list = []
    for input_string in string_list:
        the_number = input_string.rsplit(",", 1)[-1]
        if the_number.isdigit():
            numbers_list.append(the_number)
        elif skip_on_error:
            numbers_list.append("")
        else:
            raise Exception("Wrong Format occurred: %s" % (input_string))
    return numbers_list

And if you are looking for even further optimization and sure that most(if not all) strings will be of the correct format, you can even use try except if you are going to go with an integer list instead of string list. Like this:

# Instead of the if.. elif.. else construct
try:
    numbers_list.append(int(the_number))
except ValueError:
    if skip_on_error:
        numbers_list.append(0)
    else:
        raise Exception("Wrong Format occurred: %s" % (input_string))

But always remember the Zen Of Python and using split/rsplit follows these:

  1. Beautiful is better than ugly
  2. Explicit is better than implicit
  3. Simple is better than complex
  4. Readability counts
  5. There should be one-- and preferably only one --obvious way to do it

And also remember Donald Knuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%

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]
Discussions

How to extract numbers within a string?

You want to look into regular expressions (regex) and Python's re module.

import re

string = "CORSAIR VENGEANCE RGB 16GB (2X8GB) DDR4 3200MHZ CL 16"

matches = re.findall("(\d+)", string)
print(matches)

Output: ['16', '2', '8', '4', '3200', '16']

The regex pattern \d+ matches 1 or more numerical characters in sequence. By putting it in brackets ( ) it captures each occurrence of that pattern as a group. And the re.findall method returns those groups in a list. Note that they are still strings, not numbers.

More on reddit.com
๐ŸŒ r/learnpython
17
37
January 7, 2018
How to extract numbers from a string in Python? - Stack Overflow
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit() method? Example: line = "hello 12 hi 89" Resul... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to extract number from end of the string - Stack Overflow
I have a string like "Titile Something/17". I need to cut out "/NNN" part which can be 3, 2, 1 digit number or may not be present. How you do this in python? Thanks. More on stackoverflow.com
๐ŸŒ stackoverflow.com
I'm trying to extract a specific string of numbers that is between letters, sometimes followed by more numbers. How do I get just that particular string of numbers? (example below)
Are you familiar with RegEx? The python library is called 're'. This seems like a job for regular expressions. More on reddit.com
๐ŸŒ r/learnpython
8
1
June 11, 2021
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python extract numbers from string
Python Extract Numbers From String - Spark By {Examples}
May 21, 2024 - For each word, you can use the isnumeric() method to check if it consists entirely of numeric characters. If a word is numeric, you convert a string to an integer using int() and append it to the result list.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-extract-numbers-from-string
Python | Extract Numbers from String - GeeksforGeeks
November 10, 2025 - It checks each word with isdigit() and directly collects all the numeric ones in a single line. It can only extract positive numbers. ... isdigit() method checks if a character is a number. We use a loop to go through each character in the string ...
Find elsewhere
๐ŸŒ
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 - Letโ€™s look at an example to see the above steps in action in Python. # string with numbers s = "I love you 3000" # result string s_nums = "" # iterate over characters in s for ch in s: if ch.isdigit(): s_nums += ch # display the result string print(s_nums)
๐ŸŒ
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.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-32027.html
Extract continuous numeric characters from a string in Python
January 15, 2021 - I am interested in extracting a number that appears after a set of characters ('AA='). However, the issue is I: (i) am not aware how long the number is, (ii) don't know what appears right after the number (could be a blank space or ANY character exce...
๐ŸŒ
Devloprr
devloprr.com โ€บ other โ€บ extract-number-from-string-python
Extract Number From String Python
April 1, 2024 - We can use re. findall () that extracts the numbers in the string and pass \d that represents the digit by using this we easily extract numbers from the string. After that we can use for loop to iterate each element so that the string number ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-extract-numbers-from-a-string-in-Python
How to extract numbers from a string in Python?
August 10, 2023 - 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)
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python extract number from string
How to Extract Numbers From a String in Python | Delft Stack
March 11, 2025 - is there a built-in function in Python to extract numbers from strings? No, Python does not have a built-in function for this specific task, but you can easily implement it using regular expressions or list comprehensions. can I extract numbers from a string containing special characters?
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-find-number-in-string
How to Find Numbers in a String Using Python
November 4, 2025 - You can use the filter() method with string methods to extract the numbers from the string. For example, look at the code below. # Sample text containing numbers mixed with other characters text = "Room 123, Level 2, Building 45." # Use filter() to extract only the digits from the text # ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ extract-numbers-from-a-string-in-python
How To Extract Numbers From A String In Python?
March 19, 2025 - In this example, re.findall() searches ... issues with escape characters. ... Another way to extract numbers from a string is by using a combination of list comprehension and the isdigit() method in Python....
๐ŸŒ
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)
๐ŸŒ
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 numbers text = Order number 12345, amount 678.90 yuan #Use regular expressions to find all numbers numbers = re.findall(r'\d+', text)print( The numbers in the 'f' string are:{numbers}" ) In this 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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ i'm trying to extract a specific string of numbers that is between letters, sometimes followed by more numbers. how do i get just that particular string of numbers? (example below)
r/learnpython on Reddit: I'm trying to extract a specific string of numbers that is between letters, sometimes followed by more numbers. How do I get just that particular string of numbers? (example below)
June 11, 2021 -

This is such a simple question, I almost feel dumb asking it. I feel like this is a basic day one "index through a string assignment" but I can't quite get it right.

I'm going through old g-code files to extract data. Python is reading the g-code as if it were a string, and I'm making patterns to rip data out of the file and store it in a dictionary. I can't quite seem to get the pattern down for this one

So I have a string like the following:

G0Z1.210T1500000

the part I want to extract is G0Z1.210T1500000

I don't want the G0Z1.210T1500000

I only want the numbers that follow the "G0Z", and I want to throw out everything else. It keeps on adding the rest of the numbers to it

So here is what I have so far:

text = "G0Z1.210T1500000"

noGoz = text[3 : len(text) - 1]

Over_All_Length = ""

while True:
    for isNumb in noGoz:
        if isNumb.isnumeric():
            Over_All_Length += isNumb
        elif isNumb == ".":
            Over_All_Length += isNumb
        else:
            break
#    Sanity check:
print(Over_All_Length)

Instead of a while True I've done stuff like this:

KillSwitch  = "Live"
while KillSwitch == "Live"
    for isNumb in noGoz:
        if isNumb.isnumeric():
            Over_All_Length += isNumb
        elif isNumb == ".":
            Over_All_Length += isNumb
        else:
            KillSwitch = "Dead"
#    Sanity check:
print(Over_All_Length)

and this:

count = 0

if count == 0:
    for isNumb in noGoz:
        if isNumb.isnumeric():
            Over_All_Length += isNumb
        elif isNumb == ".":
            Over_All_Length += isNumb
        else:
            count += 1
#    Sanity check:
print(Over_All_Length)

I've tried all sorts of tricks where basically you set a condition for a loop to be true, and then change it when you hit the first non-number or non- period character. Nothing seems to work