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.
Jump into concepts and practice - no test required
string.isalpha() string.isdigit() string.isalnum() string.islower() string.isupper() string.isspace() string.isprintable()
"hello".isalpha() # True "hello123".isalpha() # False
"12345".isdigit() # True "123abc".isdigit() # False
"hello123".isalnum() # True "hello 123".isalnum() # False
"HELLO".isupper() # True "Hello".isupper() # False
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(" ")
isalpha() doesisalpha() method returns True if all characters in the string are alphabet letters only.isdigit() checks for digits only, isalnum() checks for letters or digits, and isspace() checks for whitespace characters.s contains only digits in Python?s.isdigit() is correct.s.isdigit misses parentheses, isdigit(s) is not a built-in function, and s.is_digit() is not a valid method.text = "Hello123" print(text.isalnum()) print(text.isalpha())
text.isalnum()isalnum() returns True.text.isalpha()isalpha() returns False.user_input = " 123 "
if user_input.isdigit():
print("Digits only")
else:
print("Not digits only")s contains only printable characters and no spaces. Which combination of methods correctly validates this?isprintable()s.isprintable() and not ' ' in s uses not ' ' in s to exclude spaces, combined with isprintable(), which is correct. s.isprintable() and not s.isspace() fails because not s.isspace() only checks if the whole string is not spaces, but allows spaces mixed with other chars. Options C and D do not correctly exclude spaces.