Python | Check Numeric Suffix in String
Last Updated :
15 May, 2023
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 can be solved using regex. The search and group function can perform the task of searching the suffix string and printing the number, if it is required.
Python3
# Python3 code to demonstrate working of
# Check Numeric Suffix in String
# Using regex
import re
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
# Using regex
# Check Numeric Suffix in String
res = re.search(r'\d+$', test_str)
# printing result
print("Does string contain suffix number ? : " + str(bool(res)))
OutputThe original string is : Geeks4321
Does string contain suffix number ? : True
Method #2: Using isdigit()
The isdigit function can be used to perform this particular task using the fact that if a number at the end, means its very last character is going to be a number, so by just checking the last character, we can prove that a string ends with a number.
Python3
# Python3 code to demonstrate working of
# Check Numeric Suffix in String
# Using isdigit()
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
# Using isdigit()
# Check Numeric Suffix in String
res = test_str[-1].isdigit()
# printing result
print("Does string contain suffix number ? : " + str(res))
OutputThe original string is : Geeks4321
Does string contain suffix number ? : True
The time complexity of this program is O(1) since it only checks if the last character of the input string is a digit using the isdigit() method.
The auxiliary space required is also O(1) since the program does not use any additional data structures and only stores the result of the isdigit() method in a boolean variable res.
Method #3: Without using inbuilt function
Python3
# Python3 code to demonstrate working of
# Check Numeric Suffix in String
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
res = False
numbers = "0123456789"
if test_str[-1] in numbers:
res = True
# printing result
print("Does string contain suffix number ? : " + str(res))
OutputThe original string is : Geeks4321
Does string contain suffix number ? : True
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 4: Using the try and except block
This method using try and except block, try to convert the last character of string to int. If it throws error i.e. not a number, returns False, otherwise returns true.
Python3
# Python3 code to demonstrate working of
# Check Numeric Suffix in String
# Using try-except block
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + test_str)
res = False
try:
int(test_str[-1])
res = True
except ValueError:
res = False
# printing result
print("Does string contain suffix number ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : Geeks4321
Does string contain suffix number ? : True
Time complexity: O(1)
Auxiliary Space: O(1)
Method 5: Using str.isdecimal() method
Python3
# Python3 code to demonstrate working of
# Check Numeric Suffix in String
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
res = False
if test_str[-1].isdecimal():
res = True
# printing result
print("Does string contain suffix number ? : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : Geeks4321
Does string contain suffix number ? : True
Time complexity: O(1)
Auxiliary Space: O(1)
Method 6: Using reduce():
Step-by-step approach:
- Import the reduce() function from the functools module.
- Initialize the string to be tested.
- Use the reduce() function to iterate through the characters of the string from the end and check if the last character is a number.
- If the last character is numeric, the lambda function returns True and the next character is checked.
- If all characters are numeric, the final value returned by reduce() is True.
- Print the result.
Python3
from functools import reduce
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
# using reduce to check if last character is numeric
res = reduce(lambda x, y: y.isnumeric(), test_str[-1], False)
print("Does string contain suffix number? : " + str(res))
#This code is contributed by Pushpa.
OutputThe original string is : Geeks4321
Does string contain suffix number? : True
Time Complexity:
The time complexity of the reduce() function is O(n), where n is the length of the input string. Since the lambda function is called once for each character in the string, the overall time complexity of the algorithm is also O(n).
Space Complexity:
The space complexity of the algorithm is O(1), since only a few variables are used to store the input string and the result, and their space requirements do not depend on the length of the string. The lambda function used in the reduce() function does not create any additional data structures that would increase the space complexity. Therefore, the overall space complexity of the algorithm is constant.
Method #7: Using a loop to iterate over the characters
- Initialize the string to be checked for a numeric suffix.
- Initialize a boolean variable res to False.
- Use a loop to iterate over the characters in the string from right to left.
- For each character, check if it is a digit using the isdigit() method.
- If the character is a digit, set res to True and break out of the loop.
- If the character is not a digit, set res to False and continue iterating over the rest of the string.
- Print the result.
Python3
# initializing string
test_str = "Geeks4321"
# printing original string
print("The original string is : " + test_str)
res = False
# use a loop to iterate over the characters in the string
for c in reversed(test_str):
# check if the character is a digit
if c.isdigit():
res = True
break
else:
res = False
# printing result
print("Does string contain suffix number? : " + str(res))
OutputThe original string is : Geeks4321
Does string contain suffix number? : True
Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(1), as the space used is constant regardless of the input size.
Similar Reads
Python Check If String is Number
In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number.Example: Using isdigit() MethodPython# Python code to check if string is numeric
6 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 program to extract numeric suffix from string
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 : 04Explanation : 04 is suffix of string and number hence extracted.Input : test_str
7 min read
Python - Check if String contains any Number
We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Increment Numeric Strings by K - Python
Given the Strings list we have to increment numeric strings in a list by a given integer K. ( Note that strings that are not numeric remain unchanged ) For example: In the list ["gfg", "234", "is", "98", "123", "best", "4"] if K = 6 then result will be ["gfg", "240", "is", "104", "129", "best", "10"
4 min read
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
Frequency of Numbers in String - Python
We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6).Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match sp
3 min read
Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task
6 min read
Python | Check if string is a valid identifier
Given a string, write a Python program to check if it is a valid identifier or not. An identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover, digits can come after gfg : valid identifier 123 : invalid identifier _abc12 : v
3 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read