Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recognize single digit in string to insert leading zero?

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?

like image 378
Jo Ko Avatar asked Dec 17 '25 21:12

Jo Ko


1 Answers

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'
like image 81
Willem Van Onsem Avatar answered Dec 20 '25 09:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!