How do I recognize one digit in a string to insert a leading zero?
In Python, I have a string with two digits or one digit:
8 5E 9C 52 30 0
On every single line in a line, I would like to add zero to it (like convert 5
to 05
) and make two digits.
We think of the division, .split(‘ ‘)
and check each one and transform each number in two digits using: .zfill(2)
.
So my question is, is there a way to recognize all one digit in a string and convert all of them to two digits by inserting a leading zero?
source to share
Well, the good thing about zfill(..)
is that if the content contains two characters, that line is left untouched. So you can just use a generator (or list comprehension) and the ' '.join(..)
result back:
result = ' '.join(x.zfill(2) for x in data.split())
What generates:
>>> data = '8 5E 9C 52 30 0'
>>> ' '.join(x.zfill(2) for x in data.split())
'08 5E 9C 52 30 00'
source to share