pythonstringdigits

Removing non numeric characters from a string in Python


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

Before:

sd67637 8

After:

676378

As I am a beginner I do not know where to start with this task.


Solution

  • The easiest way is with a regexp

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