Python program to extract numeric suffix from string
Last Updated :
13 Sep, 2024
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.
Python
# 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))
OutputThe 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.
Python
# 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))
OutputThe 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
Python
# 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))
OutputThe original string is : GFG04
Suffix number : 04
Method#4: Using list comprehension
Python
test_str = "GFG04"
# Printing original string
print("The original string is : " + str(test_str))
# Using list comprehension to extract suffix number
res = ''.join([char for char in test_str[::-1] if char.isdigit()])[::-1]
# Printing result
print("Suffix number : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : GFG04
Suffix number : 04
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#5: Using filter and join method.
Python
# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using filter method
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
res = ''.join(filter(str.isdigit, test_str[::-1]))[::-1]
# printing result
print("Suffix number : " + str(res))
#this code contributed by tvsk
OutputThe original string is : GFG04
Suffix number : 04
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#6: Using rfind() and string slicing
Step by step Algorithm:
- Find the index of the first non-digit character in the string using a lambda function and filter.
- Find the last occurrence of this non-digit character using rfind() function.
- Extract the suffix number using string slicing from the index of the non-digit character to the end of the string.
- Print the suffix number.
Python
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# using rfind() and string slicing to extract suffix numbers
temp_idx = test_str.rfind(next(filter(lambda x: not x.isdigit(), test_str[::-1])))
res = test_str[temp_idx+1:]
# printing result
print("Suffix number : " + str(res))
OutputThe original string is : GFG04
Suffix number : 04
Time Complexity: O(n), where n is the length of the string. The lambda function and filter takes O(n) time, while rfind() and string slicing takes constant time.
Space Complexity: O(1), as we are not using any extra space.
Method #7: Using rpartition() + isdigit()
- Initialize the string
- Use the rpartition() method to split the string into 3 parts - the part before the last digit, the last digit, and the part after the last digit.
- Check if the last part (the part after the last digit) is empty, which indicates that the last character was a digit.
- If the last part is not empty, there was no numeric suffix in the original string, so print an appropriate message.
- If the last part is empty, check if the middle part (the last digit) is a digit.
- If the middle part is not a digit, there was no numeric suffix in the original string, so print an appropriate message.
- If the middle part is a digit, print it as the numeric suffix.
Python
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# extracting suffix number
res = test_str.rpartition('GFG')[2]
# checking if suffix is numeric
if res.isdigit():
# printing suffix number
print("Suffix number : " + str(res))
else:
# printing error message
print("No suffix number found in string!")
OutputThe original string is : GFG04
Suffix number : 04
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), as we are creating a new string to store the extracted suffix.
Method #8: Using numpy:
- Initialize the input string.
- Convert the string to a NumPy array of characters.
- Convert the array to a string using NumPy's char module.
- Find the indices of all the numeric characters in the string using the where() method from NumPy.
- Extract the suffix numbers by joining the characters at the found indices.
- Print the extracted suffix numbers.
Python
import numpy as np
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# convert string to numpy array of characters
char_array = np.array(list(test_str))
# convert array to string using numpy's char module
char_string = np.char.mod('%c', char_array)
# find indices of all numeric characters
indices = np.where(np.char.isdigit(char_string))[0]
# extract suffix numbers
suffix_numbers = ''.join(char_array[indices])
# print result
print("Suffix number: " + suffix_numbers)
#This code is contributed by Jyothi pinjala.
Output:
The original string is : GFG04
Suffix number: 04
Time complexity:
The list() function in Python has a time complexity of O(n), where n is the length of the string. This operation is done once in our code.
The np.array() function in NumPy also has a time complexity of O(n), where n is the length of the string. This operation is also done once in our code.
The np.char.mod() function in NumPy has a time complexity of O(n), where n is the length of the string. This operation is also done once in our code.
The np.where() function in NumPy has a time complexity of O(n), where n is the length of the string. This operation is done once in our code.
The join() function in Python has a time complexity of O(n), where n is the length of the extracted suffix numbers. This operation is done once in our code.
Auxiliary Space:
The space complexity of our code depends on the length of the string. The input string is stored once as a string variable and then converted to a NumPy array, which also takes up space in memory. The space complexity is O(n), where n is the length of the string.
Similar Reads
Python program to Increment Suffix Number in String
Given a String, the task is to write a Python program to increment the number which is at end of the string. Input : test_str = 'geeks006' Output : geeks7 Explanation : Suffix 006 incremented to 7. Input : test_str = 'geeks007' Output : geeks8 Explanation : Suffix 007 incremented to 8. Method #1 : U
5 min read
Python - Extract numbers from list of strings
We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = ['apple 123', 'banana 456', 'cherry 789'] we need to extract numbers from the string in list so that output becomes [123, 456, 789].Using Regular ExpressionsThis method us
2 min read
Python - Extract String till Numeric
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 | Check Numeric Suffix in String
Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
6 min read
Python - Extract Percentages from String
Given a String, extract all the numbers that are percentages. Input : test_str = 'geeksforgeeks 20% is 100% way to get 200% success' Output : ['20%', '100%', '200%'] Explanation : 20%, 100% and 200% are percentages present. Input : test_str = 'geeksforgeeks is way to get success' Output : [] Explana
2 min read
Python program for removing i-th character from a string
In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing.Using String SlicingString slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude t
2 min read
Python - Extract Tuples with all Numeric Strings
Given a list of tuples, extract only those tuples which have all numeric strings. Input : test_list = [("45", "86"), ("Gfg", "1"), ("98", "10")] Output : [('45', '86'), ('98', '10')] Explanation : Only number representing tuples are filtered. Input : test_list = [("Gfg", "1")] Output : [] Explanatio
5 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
Python | Extract words from given string
In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
4 min read
Python Program to test if the String only Numbers and Alphabets
Given a String, our task is to write a Python program to check if string contains both numbers and alphabets, not either nor punctuations. Examples: Input : test_str = 'Geeks4Geeks' Output : True Explanation : Contains both number and alphabets. Input : test_str = 'GeeksforGeeks' Output : False Expl
4 min read