Increase a numeric string by 1

1

I want to add 1 to a counter that is represented as a string. the goal is to get the sequence of numbers later. For example: from 000570370 to 000570371.

part of the code:

 def rangeOrdemServ(self):
        db = self.conexaoBanco()
        cursor = db.cursor()
        cursor.execute("SELECT ordem_serv_num FROM ordem_serv ORDER BY id DESC LIMIT 1")
        dadosOrdemServ = cursor.fetchone()
        db.commit()
        global rec
        dados1 = [dadosOrdemServ]
        dados2 = [1]
        dados3 = (dados1) + (dados2)

        self.entrOrdServ.insert(END,dados3)

When I run this code I get the following response: [('000005703701021',), 1] , not expected 000005703701022

    
asked by anonymous 04.10.2016 / 19:29

1 answer

2

Use this function:

def incrementarStringNumericaEmUm(stringNumerica):

    qtdDigitosComZeros = len(stringNumerica)
    originalComoNumero = int(stringNumerica)
    qtdDigitosSemZeros = len(str(originalComoNumero))
    resultadoComoNumero = originalComoNumero + 1

    qtdZerosNaOriginal = qtdDigitosComZeros - qtdDigitosSemZeros


    if len(str(resultadoComoNumero)) == qtdDigitosSemZeros:
        # Não houve "vai um"
        return ('0' * qtdZerosNaOriginal) + str(resultadoComoNumero)
    else:
        # Aumentou um dígito no resultado, então precisamos colocar um zero a menos
        return ('0' * (qtdZerosNaOriginal - 1)) + str(resultadoComoNumero)

It gets a numeric string in the format you have in dadosOrdemServ and returns a numeric string with the value incremented by one. For this, it counts how many zeros it has in the original, then converts the original to an integer, increments that number by one, transforms that number into a string, and concatenates the zeros back, being careful to set zero to less if " go one ".

    
04.10.2016 / 20:25