Python | Check numeric suffix in string

Python Methods and Functions | Regular Expressions | String Variables

Method # 1: Using Regular Expressions
This problem can be solved by using regular expressions. The search and group function can perform the task of finding the suffix string and printing the number if necessary.

# Python3 code to demonstrate how it works
# Check the numeric suffix in the string
# Using regular expressions

import re

  
# initialization string

test_str = "Geeks4321"

 
# print original line

print ( "The original string is:" +   str (test_str))

 
# Using regular expressions
# Check the numeric suffix in the string

res = re.search (r ' d + $ ' , test_str)

  
# print 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 accomplish this specific task, using the fact that if the number at the end means that its the very last character will be a number, then by simply checking the last character we can prove that the string ends with a number.

# Python3 code to demonstrate how it works
# Check the numeric suffix in the string
# Using isdigit ()

  
# initialization string

test_str = "Geeks4321"

 
# printing the original line

print ( "The original string is:" + str (test_str))

 
# Using isdigit ()
# Check the numeric suffix in the string

res = test_str [ - 1 ]. isdigit ()

 
# print result

print ( "Does string contain suffix number? : " + str (res))

Output:

 The original string is: Geeks4321 Does string contain suffix number?: True 




Get Solution for free from DataCamp guru