This is what I’ve tried so far:
JavaScript
x
9
1
import re
2
string = open('old.txt').read()
3
new_str = re.sub(r'[A-Z]', '', string)
4
5
characters_to_remove = '!-+'
6
for character in characters_to_remove:
7
new_str = new_str(character, '')
8
open('new.txt', 'w').write(new_str)
9
It doesn’t work, can you explain why?
Advertisement
Answer
Should work.
This code will check with is_alpha
if the i
character is an alphabetic letter (A-Z, case unsensitive) and if it returns false, will add it to the new_string
variable.
Later, it will check if the string contains the characters to remove.
JavaScript
1
10
10
1
string = open('old.txt').read()
2
characters_to_remove = '!-+'
3
4
new_str = ''.join(i for i in string if not i.isalpha())
5
for c in characters_to_remove:
6
new_str = new_str.replace(c, "")
7
8
9
open('new.txt', 'w').write(new_str)
10
Check information for is_alpha.