Search code examples
pythonstringlambdaformatting

Python difference between string formatting


long story short. Can someone explain it to me how is it that be, simple line of code can do the same as all of the for loop written by me?

def z1(code1, code2):
   parse = lambda x: int(x.replace('-', ''))
   code1, code2 = parse(code1), parse(code2)
   print(code1, code2)
   return ["%02d-%03d" % divmod(x, 1000) for x in range(code1, code2+1)] <---

here's my solution:

def z2(code1, code2):
  codes = []
  parse = lambda x: int(x.replace('-', ''))
  code1, code2= parse(code1), parse(code2)
  for x in range(code1, code2+1):
      x = str(x)
      a = x[0:2]
      b = x[2:6]
      c = a+"-"+b
      codes.append(f"{c}")
  return codes

Solution

  • ["%02d-%03d" % divmod(x, 1000) for x in range(code1, code2+1)]
    

    This is called list comprehension, allow writing more concise code than creating empty list and then append-ing in loop. Consider following example

    squares = []
    for i in range(5):
        squares.append(i**2)
    

    is equivalent to

    squares = [i**2 for i in range(5)]