0
votes

I have a string with several numbers and need to add leading zeros to some (not all) of the numbers. Only numbers that are single digits and have a letter in front need a leading zero.

input: "Z9_M50_P3_2X_MY_STRING"

output: "Z09_M50_P03_2X_MY_STRING"

1
What did you try? Please show your effort. - DYZ

1 Answers

6
votes

Try this:

(?<=[a-zA-Z])(\d)(?!\d)

replace by this:

0\1

Regex Demo

Sample Source: ( run here )

import re

regex = r"(?<=[a-zA-Z])(\d)(?!\d)"
test_str = ("Z9_M50_P3_2X_MY_STRING")
subst = "0\\1"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)