Home > OS >  Check whether a character is an alphabet, digit or special character- PYTHON
Check whether a character is an alphabet, digit or special character- PYTHON

Time:08-11

Ques - Check whether a character is an alphabet, digit or special character

I have written a python code solution and it is working well. But when I input ("@"), I get the output as an alphabet instead of special character. Can someone tell me why and how to solve it for @.

inp = input("Enter anything : ")
if inp >= "a" and inp <= "z" or inp >= "A" and inp <= "Z":
   print("input is alphabet")
elif inp>="0":
   print("input is number")
else:
   print("special character")

CodePudding user response:

elif inp>="0" and inp<="9":
   print("input is number")

You need to specify the end for the set of numbers. Everything else should stay the same.

CodePudding user response:

You could also utilize Python's String methods isalpha() and isnumeric().

def get_char():
    """
    Prompt user for character input, or exit if user
    enters more than a single character.
    :return: The user input character.
    """
    inp = input("Enter any character: ")
    if len(inp) != 1: 
        print("Invalid entry, please try again.")
        exit(65) # os.EX_DATAERR, but portable
    return inp

def check_char(inp):
    """
    Inspect character to determine if it is alpha, numeric, or special.
    :param inp: The character to inspect.
    :return: String indicating character identification. 
    """
    if inp.isalpha():
        msg=f'{inp} is alpha char'
    elif inp.isnumeric():
        msg=f'{inp} is numeric char'
    else:
        msg=f'{inp} is special char'
    return msg
    
while True:
    print(check_char(get_char()))

CodePudding user response:

Just add a special catagory for special char

import re

inp = input("Enter anything : ")
if inp >= "a" and inp <= "z" or inp >= "A" and inp <= "Z":
   print("input is alphabet")
elif inp>="0" and inp<="9":
   print("input is number")

special_characters = "!@#$%^&*()- ?_=,<>/"
if (any(c in special_characters for c in inp)):
   print("special character")

CodePudding user response:

You could also rely on the string module and check if a group contains your input:

import string

inp = input("Enter anything : ")

if inp in string.ascii_letters:
    print("input is alphabet")
elif inp in string.digits:
    print("input is number")
else:
    print("special character")
  • Related