Skip to content
Advertisement

Trying to filter out A-Z and special characters in python

This is what I’ve tried so far:

import re
string = open('old.txt').read()
new_str = re.sub(r'[A-Z]', '', string)

characters_to_remove = '!-+'
for character in characters_to_remove:
    new_str = new_str(character, '')
open('new.txt', 'w').write(new_str)

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.

string = open('old.txt').read()
characters_to_remove = '!-+'

new_str = ''.join(i for i in string if not i.isalpha())
for c in characters_to_remove:
    new_str = new_str.replace(c, "")


open('new.txt', 'w').write(new_str)

Check information for is_alpha.

7 People found this is helpful
Advertisement