In Python, I have a string with either two digits or one digit:
8 5E 9C 52 30 0
In every one digit in the string, I would like to add a leading zero to it (e.g. convert 5 to 05) and make it two digits.
Thought of splitting, .split(‘ ‘), and checking each one by one and converting each one digit to two digits with: .zfill(2).
So my question is, is there a way to recognize all single digit in a string, and convert all of them to two digits by inserting a leading zero?
Well the nice thing about zfill(..) is that if the content contains two characters, that string remains untouched. So you can simply use a generator (or list comprehension) and ' '.join(..) the result back together:
result = ' '.join(x.zfill(2) for x in data.split())
Which generates:
>>> data = '8 5E 9C 52 30 0'
>>> ' '.join(x.zfill(2) for x in data.split())
'08 5E 9C 52 30 00'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With