Removing non numeric characters from a string

Obcure picture Obcure · Jun 27, 2013 · Viewed 73.3k times · Source

I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example:

Before:

sd67637 8

After:

676378

As i am a beginner i do not know where to start with this task. Please Help

Answer

mar mar picture mar mar · Jun 27, 2013

The easiest way is with a regexp

import re
a = 'lkdfhisoe78347834 (())&/&745  '
result = re.sub('[^0-9]','', a)

print result
>>> '78347834745'