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
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.
1 Answer. Show activity on this post. input. replaceAll(new RegExp(r"\D"), "");
The easiest way is with a regexp
import re a = 'lkdfhisoe78347834 (())&/&745 ' result = re.sub('[^0-9]','', a) print result >>> '78347834745'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With