python-3.xlistcomparezero-padding

How to check if all values in the list are the same length? And if not how to add extra digits to equalise those values?


I'm doing a little coding in Python, and I came up to the issue that some of my values and not the same length.

Desired length is 15 characters

for example:

string = ['110000111100111', '100100110011011', '001101100110', '01011010001110', '111100111001', '1101100111011']

Some of these values are different, and I want to add zeros to equalise them to the same length. Specifically by adding some zeros to those values that are shorter.

Can someone give me a hand on this?

Many thanks!

I tried comparing them and finding shorter values in the list. I'm new to this.


Solution

  • Try this:

    s = ['110000111100111', '100100110011011', '001101100110', '01011010001110', '1100111001', '1101100111011']
    
    s = [x.zfill(15) for x in s]
    

    zfill() will pad a string with zeros on the left, up to the desired string length.