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?
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'
Simple solution with a list.
Code:
def pad_hex_str(hex):
return ' '.join(['0' + h if len(h) == 1 else h for h in hex.split()])
Test code:
hex_str = '8 5E 9C 52 30 0'
print(pad_hex_str(hex_str))
Results:
08 5E 9C 52 30 00
split
and use zfill
will work fine.
st = "8 5E 9C 52 30 0"
res = ""
for i in st.split():
res += " " + i.zfill(2)
print res
#output
08 5E 9C 52 30 00
>>> re.sub(r'(\b\d\b)', r'0\1', string)
>>> '08 5E 9C 52 30 00'
Don't forget to re-import, of course