我正在制作一个程序,使用python 3.4确定车牌是否处于正确的顺序(我正在开始编程,并做一些自我指定的家庭工作)。
牌照应该是三个字母的顺序,三个数字是正确的顺序。
这是我的代码:
#Get data from user
plate = input('Enter the lisence plate number: ')
#Determine if style is old or new
if len(plate) == 6 and plate[0] >= "A" and plate[0] <= "Z"\
and plate[1] >= "A" and plate[1] <= "Z"\
and plate[2] >= "A" and plate[2] <= "Z"\
and plate[3] >= "0" and plate[1] <= "9"\
and plate[4] >= "0" and plate[4] <= "9"\
and plate[5] >= "0" and plate[5] <= "9":
verd = 'works'
else:
verd = 'Not work'
#print results
print(verd)
当我输入牌照ABC123时,它告诉我它不起作用。
我一直在尝试一切,但无法弄清楚为什么这不起作用。
任何帮助都将不胜感激。
答案 0 :(得分:3)
顺便说一句,你方法中的错误是第三种情况 -
awk '{print i, $1, $2, $3, $4}' ifile.txt > ofile.txt
将其更改为 -
and plate[3] >= "0" and plate[1] <= "9" <-------- Notice that you are using `plate[1]` instead of [3]
答案 1 :(得分:1)
一个简单的正则表达式将完成这项工作。
re.match(r'[A-Z]{3}[0-9]{3}$', s)
由于re.match
尝试从字符串的开头匹配,因此您不需要使用行锚^
的开头。
示例:强>
>>> import re
>>> def check(s):
if re.match(r'[A-Z]{3}[0-9]{3}$', s):
print('works')
else:
print('Not work')
>>> check(input('Enter the lisence plate number: '))
Enter the lisence plate number: ABC123
works
>>> check(input('Enter the lisence plate number: '))
Enter the lisence plate number: ABCDEF
Not work
>>>
答案 2 :(得分:0)
在线:
and plate[3] >= "0" and plate[1] <= "9"\
将'1'改为'3',如下所示:
and plate[3] >= "0" and plate[3] <= "9"\
答案 3 :(得分:0)
你的错误是一个错字。
and plate[3] >= "0" and plate[1] <= "9"\
与
and plate[3] >= "0" and plate[3] <= "9"\
此外,print(verd)
的缩进已关闭;它位于else
区块中,因此只有在许可证无效的情况下才会打印任何内容。
这里是您的代码,只需进行少量更改即可使其正常运行:
#Get data from user
plate = input('Enter the lisence plate number: ')
#Determine if style is old or new
if len(plate) == 6 and plate[0] >= "A" and plate[0] <= "Z"\
and plate[1] >= "A" and plate[1] <= "Z"\
and plate[2] >= "A" and plate[2] <= "Z"\
and plate[3] >= "0" and plate[3] <= "9"\ # Fixed bug here
and plate[4] >= "0" and plate[4] <= "9"\
and plate[5] >= "0" and plate[5] <= "9":
verd = 'works'
else:
verd = 'Not work'
#print results
print(verd) # Fixed bug here
但是,您的代码还有其他一些问题,因此这里有一个改进的版本:
# Get data from user
plate = input('Enter the license plate number: ')
# Determine if style is old or new
if (len(plate) == 6 and
'A' <= plate[0] <= 'Z' and
'A' <= plate[1] <= 'Z' and
'A' <= plate[2] <= 'Z' and
'0' <= plate[3] <= '9' and
'0' <= plate[4] <= '9' and
'0' <= plate[5] <= '9'):
verd = 'Valid'
else:
verd = 'Invalid'
print(verd)
你也可以这样做:
# Get data from user
plate = input('Enter the license plate number: ')
# Determine if style is old or new
if (len(plate) == 6 and
plate[:3].isupper() and plate[:3].isalpha() and
plate[3:].isdigit():
verd = 'Valid'
else:
verd = 'Invalid'
print(verd)
但一般来说,我会说最好/最干净的方法是正则表达式方法:
import re
plate = input('Enter the license plate number: ')
if re.match(r'^[A-Z]{3}[0-9]{3}$', plate):
print('Valid')
else:
print('Invalid')