Jo Ko
Jo Ko

Reputation: 7575

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?

Upvotes: 3

Views: 795

Answers (4)

Abhishek Vijayan
Abhishek Vijayan

Reputation: 753

>>> re.sub(r'(\b\d\b)', r'0\1', string)
>>> '08 5E 9C 52 30 00'

Don't forget to import re of course

Upvotes: 0

bhansa
bhansa

Reputation: 7504

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

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49784

A simple solution with a list comprehension.

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

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

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'

Upvotes: 7

Related Questions