0

I am trying to take a list of strings, and prepend an amount of zeroes to the front so that they are all the same length. I have this:

def parity(binlist):
    print(binlist)
    for item in binlist:
        if len(item)==0:
            b='000'
        elif len(item)==1:
            b='00{}'.format(item)
        elif len(item)==2:
            b='0{}'.format(item)
        binlist.remove(item)
        binlist.append(b)
        return binlist

This is binlist:

['1', '10', '11', '11']    

and i want to get this after running it:

['001', '010', '011', '011']

but I get this:

['10', '11', '11', '001']

which really confuses me. thanks for any help at all.

Sawyer
  • 97
  • 1
  • 1
  • 5

5 Answers5

4

Try this:

>>> n = "7"
>>> print n.zfill(3)
>>> "007"

This way you will have always a 3 chars string (if the number is minor than 1000)

http://www.tutorialspoint.com/python/string_zfill.htm

inigoD
  • 1,681
  • 14
  • 26
2

The native string formatting operations allow you to do this without all the trouble you're putting in. Here's an example.

x = ['1', '10', '11', '11']    

print ["{:>03s}".format(t) for t in x]
['001', '010', '011', '011']
Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
1

This is caused because you are deleting the elements in the list while iterating through the list using a for loop. Doing so does not iterate over the full list. You can use a while loop to solve this problem.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
0

You can do this in a one-liner using zfill:

>>> map(lambda binlist_item: binlist_item.zfill(3), ['1', '10', '11', '11'] )
['001', '010', '011', '011']
garnertb
  • 9,454
  • 36
  • 38
0

Fill with zeros for each item in the list

binlist = [i.zfill(3) for i in binlist]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70