Python Find Last Number in String

In this Python tutorial, I will show you “How to find the last number in a string in Python” using different approaches, including some practical examples.

While working on a project, I needed to fetch the last ID(containing numbers) from the text file, so I found different methods and techniques to get the desired output quickly.

Let me share all these methods and approaches with realistic examples; they will help you in this situation.

In this Python article, I have explained 5 ways to find the last number of the string.

Find the Last Number in String in Python

First, let’s understand the scenario clearly so you will know where you can use the methods.

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 like this:

4

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

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

First, we will use the match() method of the ‘re’ module in Python, which matches the string pattern in Python.

So, we will find the last number in the string in Python using the match() method, including the regex patterns inside the match() method as a parameter.

READ:  Difference between app and project in Django

Let’s see the practical example of getting the last digit of a string in Python using the re.match() method.

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')

Note: This method will extract the single-digit number only. If the last number is 82, it will fetch only 2, not the whole number.

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

In the above code, the last number is 1, as per our data. We are fetching that digit using the re.match() method in Python. We are using a regex pattern.
re.match('.+([0-9])[^0-9]*$',text) as per our requirement.

Let’s understand the re.match('.+([0-9])[^0-9]*$',text) pattern we are using to extract the last digit of the string:

  • 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 the character that is not a digit in Python
  • $ “: used to match the end of the string

By combining all these, we are extracting the last digit of the string in Python.

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

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.

The re.search() is used to search a pattern of the string and return a match object like this
<re.Match object; span=(5, 8), match=’its’> if the pattern is found in the string; otherwise, it will return None.

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 from 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)
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. Both the patterns will find the last digit of the number in Python.

READ:  PyTorch Tensor to Numpy

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

The re.findall() is a very powerful 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)
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.

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

We can also use a for loop if we want to get the last digit from the string in Python. 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)
How to fetch the last digit of a string in Python using for loop

In the above code, we 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.

READ:  Matplotlib save as pdf + 13 examples

Custom Function to get the last number in string in Python

We can also create our logic to extract 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.

Let me show you how to fetch the last number from a string in Python by creating a user-defined function.

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))
Custom Function to get the last number in string in Python

In the above code, we 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 we’ve created a variable, result = ”, with an empty string. When we filter the numbers from the string, we 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].

Conclusion

You learned 5 different ways to find the last number in a string in Python using Python
built-in methods like findall(), match(), search() etc. You also created a custom method with a for loop.

You may like to read: