Python how to check if input is a letter or character

前端 未结 4 596
暖寄归人
暖寄归人 2021-01-26 10:53

How can I check if input is a letter or character in Python?

Input should be amount of numbers user wants to check. Then program should check if input given by user be

4条回答
  •  离开以前
    2021-01-26 11:33

    This question keeps coming up in one form or another. Here's a broader response.

    ## Code to check if user input is letter, integer, float or string. 
    
    #Prompting user for input.
    userInput = input("Please enter a number, character or string: ") 
    while not userInput:
        userInput = input("Input cannot be empty. Please enter a number, character or string: ")
    
    #Creating function to check user's input
    inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
    def inputType():
        global inputType
        
    def typeCheck():
        global inputType
        try:
            float(userInput) #First check for numeric. If this trips, program will move to except.
            if float(userInput).is_integer() == True: #Checking if integer
                inputType = 'an integer' 
            else:
                inputType = 'a float' #Note: n.0 is considered an integer, not float
        except:
            if len(userInput) == 1: #Strictly speaking, this is not really required. 
                if userInput.isalpha() == True:
                    inputType = 'a letter'
                else:
                    inputType = 'a special character'
            else:
                inputLength = len(userInput)
                if userInput.isalpha() == True:
                    inputType = 'a character string of length ' + str(inputLength)
                elif userInput.isalnum() == True:
                    inputType = 'an alphanumeric string of length ' + str(inputLength)
                else:
                    inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
    
    #Calling function         
    typeCheck()
    print(f"Your input, '{userInput}', is {inputType}.")
    

提交回复
热议问题