0

How can I make the Code add leading zeros to my strings (containing only 1s and 0s) IF it is shorter than 8 chars?

Slowly
  • 11

1 Answers1

1

You can use a simple list comprehension to do this as in the below piece of code:

# example list to work with
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]

In [72]: res = ["0"*(8-len(s)) + s if len(s) < 8 else s for s in list_of_str]

In [73]: res
Out[73]: ['00101010', '10101010', '00011110', '00000000']
kmario23
  • 57,311
  • 13
  • 161
  • 150
  • I don't know why there was a downvote. This is a different approach to solve the same problem but not an incorrect one. – kmario23 May 05 '19 at 01:05
  • 2
    I wasn't the one who downvoted, but perhaps you can add this answer to the dupe target instead of this duplicate question. It looks like an interesting solution and people might appreciate it there. – Mihai Chelaru May 05 '19 at 01:17
  • @MihaiChelaru thanks for the constructive feedback :) That's a good suggestion! – kmario23 May 05 '19 at 01:18