Python string Testing

There are several methods to test the nature of characters in a string. These methods return either True or False. For example, if a string has only numeric digits, then isdigit() method returns True. These methods can also be applied to individual characters.

String testing methods

Method Description
isalnum() This method returns True if all characters in the string are alphanumeric (A to Z, a to z, 0 to 9) and there is at least one character; otherwise it returns False.
isalpha() Returns True if the string has at least one character and all characters are alphabetic (A to Z and a to z); otherwise, it returns False.
isdigit() Returns True if the string contains only numeric digits (0 to 9) and False otherwise.
islower() Returns True if the string contains at least one letter and all characters are in lower case; otherwise, it returns False.
isupper() Returns True if the string contains at least one letter and all characters are in upper case; otherwise, it returns False.
istitle() Returns True if each word of the string starts with a capital letter and there is at least one character in the string; otherwise, it returns False.
isspace() Returns True if the string contains only spaces; otherwise, it returns False.

Write a Python Program to check the given String

CopiedCopy Code

str = input('Enter a character:') 
ch = str[0] 
if ch.isalnum(): 
print('It is alphabet or numeric character') 
   if ch.isalpha(): 
print('It is an alphabet') 
      if ch.isupper(): 
print('It is captial letter') 
      else: 
print('It is lowercase letter') 
   else: 
print('It is a numeric digit') 
elifch.isspace(): 
print('It is a space') 
else: 
print('It may be a special character')