使用列表中的值检查字符串中的字母和数字序列(Python)

时间:2015-02-23 12:22:18

标签: python

我坚持在搜索字符串以查找特定的数字和字母序列。我需要能够搜索字符串(汽车注册号码牌)中的两个字母,两个数字然后三个字母的序列。到目前为止,我有这个:

if any(letters in carReg for letters in letters): # Good enough
    print("")
    valid+=1
    if any(numbers in carReg for numbers in numbers): # Good enough
        valid+=1

if valid==0:
    print("Invalid license plate.")
elif valid==1:
    print("Does not contain both numbers AND letters")
elif valid==2:
    print("Valid License Plate")

其中lettersnumbers只是列表:

letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]

在程序开始时声明。

上面的代码有效,但前提是输入的字符串完全由字母组成,或完全由数字组成。它不会像程序那样检查序列。

编辑:carReg由此行给出:

carReg = input("Please enter your licence plate: ")
carReg = carReg.upper()

3 个答案:

答案 0 :(得分:3)

reg = "ab11foo"

a,b,c = reg[:2],reg[2:4],reg[4:] # slice string into ll nn lll
# check a is all alpha characters, b is made up of 0123456789 and c is again alpha and length is correct
if all((a.isalpha(), b.isdigit(), c.isalpha(), len(c)== 3)):
       print("Valid reg")
else:
     print("Invalid reg")

您还可以使用集和set.issuperset

letters = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
numbers = {"1","2","3","4","5","6","7","8","9","0"}
a,b,c = reg[:2], reg[2:4],reg[4:]

if all((letters.issuperset(a), numbers.issuperset(b), letters.issuperset(c), len(c)==3 )):
    .....

答案 1 :(得分:2)

您的测试是错误的,因为您不会考虑订单和字母/数字的数量。这听起来像正则表达式的正确工作:

import re

if re.match(r"^[A-Za-z]{2}[0-9]{2}[A-Za-z]{3}$", carReg):
    print("Valid :)")
else:
    print("Invalid :(")

模式表示" AZ或az中的两个字母,然后是AZ或a-z" ^$中的2个数字0-9和其他3个字母part表示字符串必须具有该格式,没有额外的尾部或前导部分。

答案 2 :(得分:0)

使用正常if条件:

  1. 通过raw_input()方法获取用户输入。
  2. 通过字符串upper()方法转换为大写。
  3. len()方法检查用户输入的长度。
  4. 根据问题定义检查字符序列。
  5. e.g。

    letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    numbers = ["1","2","3","4","5","6","7","8","9","0"]
    
    carReg = raw_input("Please enter your licence plate: ")
    carReg = carReg.upper()
    if len(carReg)==7:
        if carReg[0] in letters and carReg[1] in letters and carReg[2] in numbers and\
        carReg[3] in numbers and carReg[4] in letters and carReg[5] in letters and\
        carReg[6] in letters:
            print "Valid licence"
        else:
            print "Wrong licence"
    
    else:
        print "Wrong licence"
    

    输出:

    $ python test.py 
    Please enter your licence plate: aa123fgr
    Wrong licence
    $ python test.py 
    Please enter your licence plate: ss12fgr             
    Valid licence
    $ python test.py 
    Please enter your licence plate: adw
    Wrong licence
    $ python test.py 
    Please enter your licence plate: 12asder
    Wrong licence