0

this is what am trying to do :

l = 4
length = 10**l #10000
for x in xrange(length): 
   password = str(username)+str("%02d"%x) #but here instead of 2 i want it to be l

as you can see i want to control the format string with a variable witch i could do on my own i tried to do it like this :

password = str(username)+str("%0"+str(l)+"d"%x)  

but it gives me an error telling me that : not all arguments converted during string formatting

s4my
  • 29
  • 1
  • 9

1 Answers1

1

You can use * format specifier:

>>> '-%0*d' % (4, 9)
'-0009'
>>> '-%0*d' % (9, 9)
'-000000009'

According to the String formatting operations documentation:

Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

Alternative using str.format:

>>> '-{:0{}}'.format(9, 4)
'-0009'
>>> '-{:0{}}'.format(9, 9)
'-000000009'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • i actually want to loop from like 0000 to 9999, but i want the length to be controlled by a variable it may be from 00 99 ..etc – s4my Sep 25 '14 at 14:29
  • @s4my, The answer is for string-formatting part (body of the `for` loop). You can reuse your `for` loop with my answer. – falsetru Sep 25 '14 at 14:30
  • @s4my, `for x in xrange(length): password = '%s-%0*d' % (username, l, x)` – falsetru Sep 25 '14 at 14:32