Home > front end >  How can i restrict letters after a number in an input in Python
How can i restrict letters after a number in an input in Python

Time:05-09

I'm a begginer in python and i wanted to know how can i restrict characters after another, in my case, after a number. In this code i want the user to give me a couple of characters, like "SDK70" and print is as valid. But if the user inputs "SDK7S0" it will print it as invalid. How can i do this? This is my code so far:

str = input("str here: ")
    
while len(str) <= 6 and len(str) >= 2:
    if str[0:2].isupper() == True:
        return str

# if there is a number, return false if after the number there's a let

CodePudding user response:

Try this:

def input_string():
    x = input('str here: ')
    if 2 <= len(x) <= 6:
        number = False
        for i in range(len(x)):
            if i < 2:
                if not x[i].isupper():
                    return False
            else:
                if not number and x[i] in [str(a) for a in range(10)]:
                    number = True
                elif number:
                    if x[i] not in [str(a) for a in range(10)]:
                        return False
        return True
    return False

CodePudding user response:

I'm not sure to understand very well your requirements but here are my thoughts.

First of all, I don't see any function (def) here so return doesn't mean a lot. but assuming we are in a function named "check_str".

Here is a solution that I get from seeing your question

def check_str(str):

    if len(str) < 2 or len(str) > 6: # Length check
        return False
    
    allowed_characters_after_numbers = ['S', 'D', 'K', '7', '0']

    previous_letter_was_number = False

    for letter in str:

        if previous_letter_was_number == True:
            if letter not in allowed_character_after_numbers:
                return False

        if letter.isnumeric(): # Test is the letter is a number
            previous_letter_was_number = True
        else:
            previous_letter_was_number = False
    else:
        return True

str = input("str here: ")

print("str is good : ", check_str(str))

CodePudding user response:

I not sure if this it fits your case, but you could just check if the string has a number, and then check if the next characters are also:

word = input()
hasNumber = False

for letter in word:
   if letter.isnumeric():
      hasNumber = True
   elif hasNumber:
      return False
return True
  • Related