Home > Net >  Python: How to append leading zeros to single digit numbers inside a string elegantly?
Python: How to append leading zeros to single digit numbers inside a string elegantly?

Time:12-12

I'd like to append leading zeros to any single digit numbers found inside the string in an elegant manner. I tried using lookaheads and lookbehinds to do so (refer to code below), but it seems to not work...

import re

print(re.sub('(?<!\d)(\d)(?!\d)', '0\1', 'GPIO_1')) # desired: GPIO_01 (getting something funny here)
print(re.sub('(?<!\d)(\d)(?!\d)', '0\1', 'GPIO_10')) # desired: GPIO_10 (no problem here)
print(re.sub('(?<!\d)(\d)(?!\d)', '0\1', 'GPIO_MAX')) # desired: GPIO_MAX (no problem here)

CodePudding user response:

Use a raw string on the replacements (and good practice on all regular expressions). r'0\1'. The regular expression needs a literal backslash, but instead gets an escape code for the Unicode code point U 0001 (a control character).

CodePudding user response:

You may either use a raw string for the regex replacement:

print(re.sub('(?<!\d)(\d)(?!\d)', r'0\1', 'GPIO_1'))  # GPIO_01

Or, double escape the first capture without a raw string:

print(re.sub('(?<!\d)(\d)(?!\d)', '0\\1', 'GPIO_1'))  # GPIO_01
  • Related