Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Check Numeric Suffix in String
Next article icon

Python | Check Numeric Suffix in String

Last Updated : 15 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Output
The 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))  

Output
The 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)) 

Output
The 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 

Output
The 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. 

Output
The 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. 

Output
The 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)) 

Output
The 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.


Next Article
Python | Check Numeric Suffix in String

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences