Python Code Demonstrating String Methods
The following Python code illustrates how to use various string methods to check the properties of a string, such as whether it consists of alphanumeric characters, lowercase letters, digits, and more.
Example: String Checks
# Filename: test.py # Author: www.runoob.com # Test Case 1 print("Test Case 1") str1 = "runoob.com" print(str1.isalnum()) # Checks if all characters are alphanumeric print(str1.isalpha()) # Checks if all characters are alphabetic print(str1.isdigit()) # Checks if all characters are digits print(str1.islower()) # Checks if all characters are lowercase print(str1.isupper()) # Checks if all characters are uppercase print(str1.istitle()) # Checks if the string follows title case print(str1.isspace()) # Checks if all characters are whitespace print("------------------------") # Test Case 2 print("Test Case 2") str2 = "runoob" print(str2.isalnum()) print(str2.isalpha()) print(str2.isdigit()) print(str2.islower()) print(str2.isupper()) print(str2.istitle()) print(str2.isspace())
Sample Output:
Test Case 1 False False False True False False False ------------------------ Test Case 2 True True False True False False
Explanation:
isalnum()
: Checks if all characters are alphanumeric (letters and numbers).isalpha()
: Checks if all characters are alphabetic (only letters).isdigit()
: Checks if all characters are digits (numbers).islower()
: Checks if all characters are lowercase.isupper()
: Checks if all characters are uppercase.istitle()
: Checks if the string is in title case (first letter of each word is uppercase).isspace()
: Checks if the string consists only of whitespace characters like spaces, tabs, and newlines.