Regex will do

import re

strings = '''
Hi my name is hazza 50 test test test

Hi hazza 60 test test test

hazza 50 test test test

hazza test test test
'''

for s in re.findall('([a-zA-Z ]*)\d*.*',strings):
    print(s)

Gives

Hi my name is hazza 

Hi hazza 

hazza 

hazza test test test
Answer from codenewbie on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-string-till-numeric
Python – Extract String till Numeric | GeeksforGeeks
April 22, 2023 - Time complexity: O(n), where n is the length of the input string. . Auxiliary space: O(1), as only constant amount of extra space is used to store the temporary index variable. ... This is yet another way in which this task can be performed. Using appropriate regex(), one can get content before possible numerics. ... # Python3 code to demonstrate working of # Extract String till Numeric # Using regex() import re # initializing string test_str = "geeks4geeks is best" # printing original string print("The original string is : " + str(test_str)) # regex to get all elements before numerics res = re.findall('([a-zA-Z ]*)\d*.*', test_str) # printing result print("Extracted String : " + str(res[0]))
Discussions

regex - Extract Number before a Character in a String Using Python - Stack Overflow
I'm trying to extract the number before character "M" in a series of strings. The strings may look like: "107S33M15H" "33M100S" "12M100H33M" so basically there would be a sets of numbers separated... 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
python - extract a number after and before some string from text using python3 - Stack Overflow
How to extract the string before and after some specific string? and only extract 12 digit numbers for roll no? input_file ="my bday is on 04/01/1997 and frnd bday on 28/12/2018, ... More on stackoverflow.com
🌐 stackoverflow.com
python - Extract a number from a string, after a certain character - Stack Overflow
Ayyyy, I need some help. I have the following strings, always in "char,num" format: s = "abcdef,12" v = "gbhjjj,699" I want to get just the digits after the comma, how do I do that without splitti... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-numbers-from-string
Python | Extract Numbers from String - GeeksforGeeks
September 16, 2024 - Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as · 5 min read Python ...
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]
🌐
Note.nkmk.me
note.nkmk.me › home › python
Extract a Substring from a String in Python (Position, Regex) | note.nkmk.me
April 29, 2025 - Note that only integers (int) are allowed for indexing [] and slicing [:]. If you attempt to use division / inside indexing or slicing, it will raise an error because the result is a floating-point number (float). The following example uses integer division //, which truncates the decimal part. s = 'abcdefghi' print(len(s)) # 9 # print(s[len(s) / 2]) # TypeError: string indices must be integers print(s[len(s) // 2]) # e print(s[:len(s) // 2]) # abcd print(s[len(s) // 2:]) # efghi ... In Python, you can use regular expressions (regex) with the re module of the standard library. ... Use re.search() to extract the first substring that matches a regex pattern.
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%

Find elsewhere
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python extract numbers from string
Python Extract Numbers From String - Spark By {Examples}
May 21, 2024 - You can extract numbers from a string using list comprehension and the isdigit() method. For instance, you can start with an input string string that contains a mix of letters, numbers, and punctuation.
🌐
Finxter
blog.finxter.com › home › learn python blog › extracting numbers from a string with python
Extracting Numbers From A String With Python - Be on the Right Side of Change
April 3, 2021 - A Quick Introduction To Python’s ‘re’ Module “How to extract digits or numbers from a string” is a common search by Python users in Google, and a frequent query in forums such as Stack Overflow. The answers invariably talk to two main solutions and in this article, I intend to focus down on one of ...
🌐
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.
🌐
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)
🌐
AskPython
askpython.com › python › string › extract-digits-from-python-string
2 Easy Ways to Extract Digits from a Python String - AskPython
May 5, 2026 - Manual extraction was not happening, so I wrote a small Python script to do it automatically. That script is what this article is about. This article covers two ways to extract digits from a Python string — using isdigit() and using regex.
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-extract-first-digit-of-number
How to Extract Digits from Numbers and Strings in Python | Tutorial Reference
March 29, 2025 - match.group(0): Returns the entire matched substring (the number). match.start() returns the index of the start of the match. int(...): Converts the matched string to an integer.