To check if a string contains only alphabets and numbers in Python, you can use regular expressions from the re
module.
In this example,
re
module to use regular expressions.re.match
function to check if the string matches the pattern.containsOnlyAlphabetsAndNumbers
will be a match object, otherwise None
.import re
str = "Hello123"
pattern = "^[a-zA-Z0-9]+$"
match = re.match(pattern, str)
containsOnlyAlphabetsAndNumbers = bool(match)
print("String contains only alphabets and numbers:", containsOnlyAlphabetsAndNumbers)
String contains only alphabets and numbers: True
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Python language with well detailed examples.