Python实现随机生成车牌号

注意:

这里的代码只是简单模拟一下生成车牌号,实际应用的车牌号应该还会有很多约束的

#随机生成一个车牌号码
def car_num():
 
    char0=["京","津","沪","渝","冀","豫","云","辽","黑","湘","皖","鲁","新","苏","浙","赣","鄂","桂","甘","晋","蒙","陕","吉","闽","赣","粤","青","藏","川","宁","琼"] #省份简称
    char1='ABCDEFGHJKLMNPQRSTUVWXYZ'#车牌号中没有I和O
    char2='0123456789ABCDEFGHJKLMNPQRSTUVWXYZ'


    id_1=random.choice(char0)     #车牌号第一位     省份简称
    id_2=''.join(random.sample(char1, 1))    #车牌号第二位

    while True:
        id_3=''.join(random.sample(char2, 5))
        v=id_3.isalpha() #所有字符都是字母时返回 true
        if v==True:
           continue
        else:
           car_id=id_1+id_2+id_3
           #print car_id
           break
 
    return car_id
 
 
 
import random
import re
def car_num(len=6):
    char0='京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽赣粤青藏川宁琼'
    char1='ABCDEFGHJKLMNPQRSTUVWXYZ'#车牌号中没有I和O,可自行百度
    char2='1234567890ABCDEFGHJKLMNPQRSTUVWXYZ'
    char3='1234567890'
    len0=len(char0)-1
    len1 = len(char1) - 1
    len2 = len(char2) - 1
    len3 = len(char3) - 1
    while True:
        code = ''
        index0 = random.randint(1,len0 )
        index1 = random.randint(1, len1)
        code += char0[index0]
        code += char1[index1]
        code+=' '
        for i in range(1, 5):
            index2 = random.randint(1, len2)
            code += char2[index2]
        index3=random.randint(1,len3)
        code+=char3[index3]
        test=re.match('^.\w.[A-Z]\d{4}$|^.\w.\d[A-Z]\d{3}$|^.\w.\d{2}[A-Z]\d{2}$|^.\w.\d{3}[A-Z]\d$|^.\w.\d{5}$',code)
        if test:
            return code


你可能感兴趣的:(Python,python,random)