繁体   English   中英

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

[英]Checking a string for a sequence of letters and numbers using values from a list (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()
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和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 )):
    .....

您的测试是错误的,因为您没有考虑顺序和字母/数字的计数。 这听起来像是正则表达式的正确工作:

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,然后是2位数字0-9,另外3个字母用AZ或az”^$部分表示字符串必须具有确切的格式,没有多余的结尾或前导部分。

if情况下使用普通:

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

例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM