Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove a character and specific immediately trailing characters in python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading