I have a list of strings in python of the form ABC_### where ### is a number from 1-999. I want to remove the _ and any leading 0s from the number, basically any _, _0, or _00 to get the format ABC 4 or ABC 909. I can think of a couple of dumb ways to do this but no smart ways, so I’m here 🙂
>Solution :
You can use this regex:
_0*
which matches zero or more 0‘s after an _, and replace it with ' '.
import re
strs = ['ABC_2545', 'ABC_001', 'ABC_04']
for s in strs:
print(re.sub(r'_0*', ' ', s))
Output:
ABC 2545
ABC 1
ABC 4