1

Padding a number with leading zeros has been answered here. But in my case I have a string character followed by digits. I want to add leading zeros after the string character, but before the digits, keeping the total length to 4. For example:

A1 -> A001
A12 -> A012
A123 -> A123

I have the following code that gets me what I want, but is there a shorter way to do this without using re to split my string into text and numbers first?

import re
mystr = 'A4'
elements = re.match(r"([a-z]+)([0-9]+)", mystr, re.I)
first, second = elements.groups()
print(first + '{:0>3}'.format(second))

output = A004
Community
  • 1
  • 1
Murchak
  • 183
  • 1
  • 3
  • 17

1 Answers1

0

You could use the following to avoid using re:

def pad_center(s):
    zeros = '0' * (4 - len(s))
    first, *the_rest = list(s)
    return first + zeros + ''.join(the_rest)

print(pad_center('A1'))
print(pad_center('A12'))
print(pad_center('A123'))

Or, if you want to use format() you could try this:

def pad_center(s):
    zeros = '0' * (4 - len(s))
    first, *the_rest = list(s)
    return '{}{}{}'.format(first, zeros, ''.join(the_rest))

However, I am not aware of any way to add padding to the center of a string with the format string syntax without prior processing.

elethan
  • 16,408
  • 8
  • 64
  • 87