Home > front end >  PYTHON- Return minimum three digits
PYTHON- Return minimum three digits

Time:02-04

I want to return minium three digits maximum whatever it has it should return.

I have tried following function,

def get_code(model, prefix):
    content = model.objects.filter(code__startswith=prefix).last()
    last = None
    code_prefix = prefix
    if content:
        a_string = content.code
        split_strings = []
        n = len(prefix)
        for index in range(0, len(a_string), n):
            split_strings.append(a_string[index: index   n])
        last = int(split_strings[1])
    if last is not None:
        suggested = last   1
    else:
        suggested = 1
    return "{}{:03d}".format(code_prefix, suggested)

Above code returns threedigits only if i have 4 didits it skips for calculation also. it takes only three digits for calucualtion also. how can i fix this???

CodePudding user response:

If you replace the last line with

while len("" suggested)<3:
    suggested="0" suggested
return code_prefix suggested

I think you will have the formatting that you want. We have to concatenate to a string to use len and to keep the 0's.

CodePudding user response:

here my answer,

def get_code(model, prefix):
    content = model.objects.filter(code__startswith=prefix).last()

    def text_num_split(item):
        for index, letter in enumerate(item, 0):
            if letter.isdigit():
                return [item[:index], item[index:]]
    last = None
    code_prefix = prefix
    if content:
        a_string = content.code
        pre_code = text_num_split(a_string)
        last = int(pre_code[-1])
    if last is not None:
        suggested = last   1
    else:
        suggested = 1
    return "{}{:03d}".format(code_prefix, suggested
  •  Tags:  
  • Related