Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading