0
0
Pythonprogramming~5 mins

String validation checks in Python

Choose your learning style9 modes available
Introduction
String validation checks help us confirm if a text meets certain rules, like if it has only letters or numbers. This is useful to make sure data is correct before using it.
Checking if a username contains only letters and numbers before saving it.
Verifying if a password has at least one uppercase letter and one digit.
Making sure a phone number contains only digits.
Confirming that an input is not empty and contains printable characters.
Validating if a string is all lowercase or uppercase for formatting.
Syntax
Python
string.isalpha()
string.isdigit()
string.isalnum()
string.islower()
string.isupper()
string.isspace()
string.isprintable()
These methods return True if the string meets the condition, otherwise False.
They do not change the string, only check it.
Examples
Checks if all characters are letters.
Python
"hello".isalpha()  # True
"hello123".isalpha()  # False
Checks if all characters are digits.
Python
"12345".isdigit()  # True
"123abc".isdigit()  # False
Checks if all characters are letters or digits, no spaces.
Python
"hello123".isalnum()  # True
"hello 123".isalnum()  # False
Checks if all letters are uppercase.
Python
"HELLO".isupper()  # True
"Hello".isupper()  # False
Sample Program
This program tests different string validation methods on various example strings and prints the results.
Python
def check_string(s):
    print(f"String: '{s}'")
    print(f"Is alphabetic? {s.isalpha()}")
    print(f"Is numeric? {s.isdigit()}")
    print(f"Is alphanumeric? {s.isalnum()}")
    print(f"Is lowercase? {s.islower()}")
    print(f"Is uppercase? {s.isupper()}")
    print(f"Is space only? {s.isspace()}")
    print(f"Is printable? {s.isprintable()}")

check_string("HelloWorld")
print()
check_string("12345")
print()
check_string("Hello123")
print()
check_string("   ")
OutputSuccess
Important Notes
Empty strings return False for most checks except isprintable().
Whitespace characters count as printable but not as letters or digits.
Use these checks to avoid errors when processing user input.
Summary
String validation checks help confirm what kind of characters a string contains.
Common methods include isalpha(), isdigit(), isalnum(), islower(), isupper(), isspace(), and isprintable().
These methods return True or False and are useful for input validation.