Reputation: 511
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"
Upvotes: 0
Views: 773
Reputation: 10466
Try this:
(?<=[a-zA-Z])(\d)(?!\d)
replace by this:
0\1
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)
Upvotes: 7