Skip to content
Related Articles

Related Articles

Python program to extract numeric suffix from string

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Jul, 2022

Given a string of characters with digits embedded in it. The task is to write a Python program to extract all the numbers that are trailing, i.e at the suffix of the string. 

Examples:

Input : test_str = “GFG04”

Output : 04

Explanation : 04 is suffix of string and number hence extracted.

Input : test_str = “GFG143”

Output : 143

Explanation : 143 is suffix of string and number hence extracted.

Method #1 : Using loop + isdigit() + slicing 

In this, the string is reversed using slicing, and occurrence of 1st non-digit element is recorded using isdigit, and at last, list is sliced till the element and reversed again to get the suffix number.

Python3




# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using loop + isdigit() + slicing
 
# initializing string
test_str = "GFG04"
 
# printing original string
print("The original string is : " + str(test_str))
 
# loop for fetching the 1st non digit index
rev_str = test_str[::-1]
temp_idx = 0
 
for idx, ele in enumerate(rev_str):
    if not ele.isdigit():
        temp_idx = idx
        break
 
# reversing the extracted string to
# get number
res = rev_str[:temp_idx][::-1]
         
# printing result
print("Suffix number : " + str(res))


Output

The original string is : GFG04
Suffix number : 04

Method #2: Using regex

Appropriate regex can be employed to solve this problem. Provides a compact solution to the problem.

Python3




# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using regex
import re
 
# initializing string
test_str = "GFG04"
 
# printing original string
print("The original string is : " + str(test_str))
 
# regex to extract number
res = re.search(r"(\d+)$", test_str).group()
         
# printing result
print("Suffix number : " + str(res))


Output

The original string is : GFG04
Suffix number : 04

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3: Without isdigit() method

Python3




# Python3 code to demonstrate working of
# Extract Suffix numbers
 
# initializing string
test_str = "GFG04"
 
# printing original string
print("The original string is : " + str(test_str))
 
# loop for fetching the 1st non digit index
rev_str = test_str[::-1]
temp = 0
digits = "0123456789"
for i, ele in enumerate(rev_str):
    if not ele in digits:
        temp = i
        break
 
# reversing the extracted string to
# get number
res = rev_str[:temp][::-1]
         
# printing result
print("Suffix number : " + str(res))


Output

The original string is : GFG04
Suffix number : 04

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!