HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Padding a hexadecimal string with zeros

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
paddingzeroshexadecimalwithstring

Problem

I'm given a hexadecimal number in string form with a leading "0x" that may contain 1-8 digits, but I need to pad the number with zeros so that it always has 8 digits (10 characters including the "0x").

For example:

  • "0x123" should become "0x00000123".



  • "0xABCD12" should become "0x00ABCD12".



  • "0x12345678" should be unchanged.



I am guaranteed to never see more than 8 digits, so this case does not need to be handled.

Right now, I have this coded as:

padded = '0x' + '0' * (10 - len(mystring)) + mystring[2:]


It works, but feels ugly and unpythonic. Any suggestions for a cleaner method?

Solution

Perhaps you're looking for the .zfill method on strings. From the docs:

Help on built-in function zfill:

zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.


Your code can be written as:

def padhexa(s):
    return '0x' + s[2:].zfill(8)

assert '0x00000123' == padhexa('0x123')
assert '0x00ABCD12' == padhexa('0xABCD12')
assert '0x12345678' == padhexa('0x12345678')

Code Snippets

Help on built-in function zfill:

zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.
def padhexa(s):
    return '0x' + s[2:].zfill(8)

assert '0x00000123' == padhexa('0x123')
assert '0x00ABCD12' == padhexa('0xABCD12')
assert '0x12345678' == padhexa('0x12345678')

Context

StackExchange Code Review Q#67611, answer score: 13

Revisions (0)

No revisions yet.