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

Removing numbers from string while keeping alphanumeric words

I want to remove numeric values without losing numbers that are part of alphanumeric words from a string.

String = "Jobid JD123 has been abended with code 346"

Result = "Jobid JD123 has been abended with code"

I am using the following code:

result = ''.join([i for i in String if not i.isdigit()])

which gives me the result as ‘Jobid JD has been abended with code

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

Is there anyway we can remove the words that only contain digits, while retaining those that contain a mix of letters and digits?

>Solution :

You can use regex to find runs of one or more digits \d+ between two word boundaries \b, and replace them with nothing.

>>> import re
>>> string = "Jobid JD123 has been abended with code 346"
>>> re.sub(r"\b\d+\b", "", string).strip()
'Jobid JD123 has been abended with code'

Note that the regex doesn’t get rid of the trailing space (between "code" and the digits), so you need to strip() the result of the re.sub().

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