简体   繁体   中英

Add leading zeros to numbers within string

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM