字母后面跟一个数字的字符串输入验证

时间:2012-12-19 18:02:25

标签: python python-3.x

我希望userinput的格式为字母编号。这封信应该 来自A-H且数字应介于1-7之间,例如A4H7。 我不希望userinput是例如AAAAA2B22。 这是我到目前为止所做的:

x=input("Write something:")

if len(x) !=2:
    print("Wrong")

letter=x[0]
number= x[1]

if number >=8:
    print("Wrong")

if letter not ["A","B","C","D","F","G"]:
    print("Wrong")

if letter == int:
    print("Wrong")

if number == str:
    print("Wrong")

else:
    print("Perfect")

4 个答案:

答案 0 :(得分:4)

我会使用regular expression匹配来执行此操作:

import re

x=input("Write something: ")

if re.match('^[A-H][1-7]$',x):
     print('Perfect!')
else:
     print ('Wrong')

正则表达式'^[A-H][1-7]$'x必须适合的模式。

^      # This character matches the start of the string
[A-H]  # After the start of the string we allow the group A-H (A,B,C,D,E,F,G,H)
[1-7]  # The next character must be a digit between 1 and 7
$      # This character matches the end of the string

使用锚点^,$意味着x的长度必须为2,这是隐含的,因此我们不需要单独检查。

一种改进,循环直到收到正确的值:

import re

while not re.match('^[A-H][1-7]$',input("Write something: ")):
     print('Wrong')

print('Perfect!')

演示:

Write something: 11
Wrong
Write something: AA
Wrong
Write something: a1
Wrong
Write something: A9
Wrong
Write something: A1
Perfect!

答案 1 :(得分:1)

if letter == int:
    print("Wrong")

if number == str:
    print("Wrong")

这不会有两个原因。首先,在这种情况下,字母和数字在技术上总是字符串。键盘的任何输入都是一个字符串,即使它是一个数字。第二,==运算符用于比较两个对象的相等性(这里的“对象”包括字符串或整数甚至类)并且与询问不同,“此对象是此类的实例”

我同意其他答案,因为你最好用正则表达式服务,但是如果你只想使用条件来判断字符串是单字符数字还是字母,你可以使用字符串方法来完成:

if not letter.isalpha():
    print("Wrong")

if not number.isdigit():
    print("Wrong")

答案 2 :(得分:0)

这是正则表达式的完美用例,

import re
x = input("Write something")
if re.match("^[A-H][1-7]$", x):
    print("Perfect")

答案 3 :(得分:0)

使用正则表达式的完美场景

import re
x=input("Write something: ")
print("Perfect" if re.match('^[A-H][1-7]$', x) else "Wrong")