python-3.xdjangodjango-views

How to convert the last number of Str = (2021GC110) in Int on Python


I'm a beginner in Django and i trying convert Str where the base for this is (2021(year) - CG(product name) - 1(ID product) -101 (var the product).

But I need the last number for variable.

Example:

product 1: 2021CG1101
product 2: 2021CG1102

This is my view.py:

    if serialNumberForm.is_valid():
        os = serialNumberForm.save(commit=False)
        Produto.numeroSerie = NumeroSerie.id
        os.numeroSerie = id
        lastProduct = NumeroSerie.objects.last()
        
        if lastProduct == None:
            prefix = datetime.date.today().year
            fix = product.nome[3:6]
            suffix = Produto.id
            var = 10
            os.serialNumber = str(prefix) + fix + str(suffix) + str(var)
            
        elif int(lastProduct.serialNumber[0:3]) != datetime.date.today().year:
            prefix = datetime.date.today().year
            fix = product.nome[3:6]
            suffix = Produto.id
            var = 10
            os.serialNumber = str(prefix) + fix + str(suffix) + str(var)
       
        else:
            prefix = datetime.date.today().year
            fix = product.nome[3:6]
            suffix = NumeroSerie.produto(os)
            var = (lastProduct.serialNumber[-1]) =+ 1
            os.serialNumber = str(prefix) + fix + str(suffix) + str(var)
        
        os.save()
        

Solution

  • This looks like a task for regular expressions:

    import re
    reg = re.compile(r"(?P<year>\d{4})(?P<group>[A-Z]{2})(?P<number>\d+)")
    match = reg.match("2021CG1101")
    if match is not None:
        result = match.groupdict()
        print(result['year'])
        print(result['group'])
        print(result['number'])