Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to accept string ending with alphanumeric character
When it is required to check if a string ends with an alphanumeric character or not, regular expressions can be used. An alphanumeric character is any letter (a-z, A-Z) or digit (0-9). This tutorial demonstrates how to create a function that validates whether a string's last character is alphanumeric.
Using Regular Expressions
The re.search() method can match patterns at the end of a string using the $ anchor ?
import re
regex_expression = '[a-zA-Z0-9]$'
def check_string(my_string):
if re.search(regex_expression, my_string):
print("The string ends with alphanumeric character")
else:
print("The string does not end with alphanumeric character")
# Test with string ending with special character
my_string_1 = "Python@"
print("The string is:")
print(my_string_1)
check_string(my_string_1)
# Test with string ending with digit
my_string_2 = "Python1245"
print("\nThe string is:")
print(my_string_2)
check_string(my_string_2)
The string is: Python@ The string does not end with alphanumeric character The string is: Python1245 The string ends with alphanumeric character
Using Built-in String Methods
You can also use the isalnum() method to check the last character ?
def check_alphanumeric_ending(text):
if text and text[-1].isalnum():
print(f"'{text}' ends with alphanumeric character")
return True
else:
print(f"'{text}' does not end with alphanumeric character")
return False
# Test cases
test_strings = ["Hello123", "World!", "Test#", "Python3", ""]
for string in test_strings:
check_alphanumeric_ending(string)
print()
'Hello123' ends with alphanumeric character 'World!' does not end with alphanumeric character 'Test#' does not end with alphanumeric character 'Python3' ends with alphanumeric character '' does not end with alphanumeric character
How the Regular Expression Works
[a-zA-Z0-9] − Character class matching any letter or digit
$ − Anchor that matches the end of the string
re.search() − Returns a match object if pattern is found, None otherwise
Comparison of Methods
| Method | Pros | Cons |
|---|---|---|
| Regular Expression | Flexible pattern matching | Requires regex knowledge |
isalnum() |
Simple and readable | Only works for single character check |
Conclusion
Use regular expressions with [a-zA-Z0-9]$ pattern for flexible string validation. For simple cases, the isalnum() method on the last character provides a more readable solution.
