How to Get Last Number in Python String

I was working on a project where I had to clean up messy text data coming from customer feedback forms.

Some of these strings contained numbers mixed with words, and I specifically needed to get last number in Python string. At first, I thought there would be a built-in function, but there isn’t.

So, I explored a few simple methods that worked well for me. In this tutorial, I’ll show you different approaches to get the last number from a Python string.

Find the Last Number in a String in Python

First, let’s understand the scenario clearly. Suppose I have a text file with a large amount of data containing the Employee’s ID and name, like this:

Employee_Data = "1 : George , 2 : Peter, 3 : Jake, 4 : Lisa"

Now, it will take more time if we want to know which ID is the last and can’t scroll down repeatedly to find the last ID. At this point, these methods will be helpful for us and give the required output.

4

Let’s understand all the methods one by one with examples

Method 1: Use Python’s re.match() Method

I will explain how to use the match() method of the ‘re’ module in Python, which matches the string pattern in Python.

import re

text = 'India": +91,"United Kingdom": +44,"Japan": +81,"United States": +1,"Australia": ? '

match = re.match('.+([0-9])[^0-9]*$',text)

if match:
    print('The last number is:', match.group(1))
else:
    print('The given string does not have any number')

You can see the output in the screenshot below.

Python find last number in string using re.match() method

This method will extract the single-digit number only. If the last number is 82, it will fetch only 2, not the whole number. Let’s understand the re.match(‘.+([0-9])[^0-9]*$’,text) pattern.

  • re.match(): Used to match the string pattern.
  • .+ “: this pattern matches any character one or more times.
  • ([0-9]): This pattern matches a single digit
  • [^0-9]*: It will match a character that is not a digit in Python
  • $ “: used to match the end of the string

Method 2: Use re.search() Method in Python

In the previous example, we are fetching the last single-digit number, but what if we want to extract the last whole number in a string? To solve that issue, we can use the re.search() method, a built-in method of the re module.

Syntax:

re.search("pattern", "string")
  • re.search(“pattern”, “string”): Before using re.search() method, you have to import re module first.
  • (“pattern”, “string”): A pattern is the word or character you search for in the string.
import re

text = 'India": +91,"United States": +1,"United Kingdom": +44,"Japan": +81,"Australia": ? '

result2 = re.search(r'\d+', text[::-1]).group()[::-1]
result3 = re.search(r'(\d+)\D+$', text).group(1)

print(result2)
print(result3)

You can see the output in the screenshot below.

How to get the last digit from the string using re.search() method in Python

In the above code, we are including two different logics inside the re.search() method and get the same output from both these “re.search(r’\d+’, text[::-1]).group()[::-1]” and “re.search(r'(\d+)\D+$’, text).group(1)” patterns.

Method 3: Use Python’s re.findall() Method

The re.findall() is a very efficient and easy method in Python to search for any pattern in a string. If the pattern matches the string, it will return all occurrences in the list; otherwise, it will return an empty list.

Syntax

re.findall("pattern", "string") 
  • re.findall(“pattern”, “string”): One more parameter is there called flag = 0, which is an optional parameter, and we will not use this parameter as per our requirement.
import re

text = 'India": +91,"United States": +1,"United Kingdom": +44,"Japan": +81,"Australia": ? '

result = re.findall(r'\d+', text)[-1]

print(result)

You can see the output in the screenshot below.

Write a program to find the last digit from the string using re.findall() method

We have the country dial code data in string format in the code, and I want to get the last dial code from the data. So we are using the re.findall() method and targeting all the numbers existing in the string using ” \d ” like this “result = re.findall(r’\d+’, text)[-1]”.\ And [-1] will take the last element from the list.

Method 4: Use a Python For Loop

We can also use a for loop to get the last digit from the Python string. Also, we are using a break statement in the example to stop the loop when it satisfies the condition.

string = "1 : George , 2 : Peter, 3 : Jake, 4 : Lisa"
for i in range(len(string) - 1, -1, -1):
    if string[i].isdigit():
        last_number = string[i]
        break
print(last_number)

You can see the output in the screenshot below.

How to fetch the last digit of a string in Python using for loop

I have data of employees with their IDs, and I want to fetch the last ID from the data. We are using a for loop to target every character of the string and check whether it is a digit. If it is, we initialize another variable called last_number and then use a break statement to exit the loop.

Method 5: Use Custom Function

We can also create our logic to get the last number of strings in Python by combining different built-in methods like split(), append(), isdigit(), etc., in one program.

These methods will not directly give you the desired output. You must understand how they work and where the technique must be applied.

def get_last_num(st):
    result = ''
    for i in st:
        if i.isdigit():
            result+=i
        else:
            result+=','

    result1 = result.split(',')
    output = []
    
    for i in result1:
        if i != '':
            output.append(i)
    
    return f"Last Number of the string :{output[-1]}"

str = 'ge45orge34@gmail.com'
print(get_last_num(str))

You can see the output in the screenshot below.

Custom Function to get the last number in string in Python

In the above code, I have one Email ID, “str = ‘ge45orge34@gmail.com’,” which contains two different numbers. I want to fetch the last number, 34, from the string.

So I’ve created a variable, result = ”, with an empty string. When I filter the numbers from the string, I will store those numbers in the result.

Then, we initialized a for loop ” for i in st: “to target every input string character and put a condition inside the for loop. If the character is a digit, add that character inside the result; otherwise, add a comma.

Then, using the split() method, all the numbers are entered into the list. The last number is removed from the list using [-1].

I helped you to learn five different ways to get last number in Python string using built-in methods like findall(), match(), search() etc, I also explained to you how to create a custom method with a for loop.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.