Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing non numeric characters from a string

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

like image 666
Obcure Avatar asked Jun 27 '13 07:06

Obcure


People also ask

How do I remove a character from a number string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove all non numeric characters from a string Dart?

1 Answer. Show activity on this post. input. replaceAll(new RegExp(r"\D"), "");


2 Answers

The easiest way is with a regexp

import re a = 'lkdfhisoe78347834 (())&/&745  ' result = re.sub('[^0-9]','', a)  print result >>> '78347834745' 
like image 51
mar mar Avatar answered Sep 20 '22 04:09

mar mar


Loop over your string, char by char and only include digits:

new_string = ''.join(ch for ch in your_string if ch.isdigit()) 

Or use a regex on your string (if at some point you wanted to treat non-contiguous groups separately)...

import re s = 'sd67637 8'  new_string = ''.join(re.findall(r'\d+', s)) # 676378 

Then just print them out:

print(old_string, '=', new_string) 
like image 34
Jon Clements Avatar answered Sep 21 '22 04:09

Jon Clements