如何验证用户的输入,直到他们输入正确的格式,然后我如何摆脱布尔循环?(Python 3.4)



所以我正在尝试获得一个特定的格式。我需要用户只输入字母A到J以及数字1-10之间的值。我还需要用户在在中间输入一个空格。我需要不断询问用户,直到他们输入以下内容"A4"或"J10"。我一直在询问用户可能输入的所有类型的内容,但我也屏蔽了我想要的格式,我真的不知道该怎么办,因为我已经尝试了一段时间了。

我的while循环试图排除各种无效输入,如"4D"、"D"、4、"Y9"。

但我希望while循环在用户输入类似"A1"或"G7"的内容后停止。

alphabet = ['A', 'B', 'C' ,'D' ,'E', 'F', 'G', 'H', 'I', 'J']
numbers = ['1','2','3','4','5','6','7','8','9','10']
enterCoordinate  = input('Enter coordinates x y (x in [A..J] and y in [1..10]) or s for ship status: ')
enterCoordinateL = enterCoordinate.lower()    
coordinates = enterCoordinate.split()

while (len(enterCoordinate) <= 2) or (len(enterCoordinate) >= 4) or   
(enterCoordinate[1] != ' ') or (enterCoordinate[0] not in alphabet) or 
(coordinates[1] not in numbers):
    enterCoordinate  = input('Enter coordinates x y (x in [A..J] and y in 
    [1..10]) or s for ship status: ')
    if (enterCoordinate[0] in alphabet) and (enterCoordinate[1] == ' ')  and 
        (coordinates[1] in numbers) and len(enterCoordinate) == 3:
            ty = input('The format is right now. ')
alphabet = ['A', 'B', 'C' ,'D' ,'E', 'F', 'G', 'H', 'I', 'J']
numbers = ['1','2','3','4','5','6','7','8','9','10']
while True:
    enterCoordinate  = list(input('Enter Something '))
    if len(enterCoordinate) >= 4:
        enterCoordinate = enterCoordinate[:2] + [''.join(enterCoordinate[2:4])]
    elif len(enterCoordinate) <=2:
        print('Your input is invalid')
        continue
    if not enterCoordinate[0] in alphabet:
        print('First element is invalid')
        continue
    elif enterCoordinate[1] != ' ':
        print('Second element is invalid')
        continue
    elif not enterCoordinate[2] in numbers:
        print('Third element is invalid')
        continue   
    break

您可以使用正则表达式来检查您的模式:

import re
my_pattern=re.compile("^[A-J] [0-9]|10$")
my_strings=["A 4","J 10","4 D","d 4","Y 9"]
for my_string in my_strings:
    if my_pattern.match(my_string):
        print(my_string)

相关内容

  • 没有找到相关文章

最新更新