Search code examples
pythonstringalphadigit

python string must contain 1 digit and 1 letter


I made a funtion that requires input of 2 values in a string. I'm trying to make it so that the input must consist of a combination of 1 digit and 1 letter. Example: 3f 5h I have the following code but i can't seem to get the condition of digit and alpha to work. Is it because .isdigit and .isalpha are about all characters?

def chess(value1, value2):

    if len(value1) == 2 and len(value2) == 2:
        for char in value1, value2:
            if char.isalpha() and char.isdigit():
                print("Input is right format.")
            else:
                print("Input is NOT right format.")
    else:
        print("Input is NOT right format.")

value1, value2 = input('values: ') .split()

chess(value1, value2) 

Using only

if char.isalpha():

or

if char.isdigit():

seems to work. But together they don't.


Solution

  • I am assuming you have no clue about regex with my answer but you could do something like this and write a function to check if each space is valid.

    def validSpaceFormat(space):
        if len(space) == 2:
            if space[0].isalpha() and space[1].isdigit():
                return True
        return False 
    
    def chess(value1, value2):
        if validSpaceFormat(value1) and validSpaceFormat(value2):
           print("Input correct.")
        else:
            print("Input wrong.")
    
    value1, value2 = input('values: ').split()
    chess(value1, value2) 
    

    This is assuming that people will always input moves as "X1 Y2"

    isalpha() and isdigit() only work on characters so you need to index each character in the string to check what it is.