Samuel fisher
Samuel fisher

Reputation: 11

Python replace/delete special characters

character = (%.,-();'0123456789-—:`’)
character.replace(" ")
character.delete()

I want to delete or replace all the special characters and numbers from my program, I know it can be done in the one string just not sure how to space all the special characters with quotes or anything. Somehow I'm supposed to separate all the special character in the parenthesis just not sure how to break up and keep all the characters stored in the variable.

Upvotes: 0

Views: 353

Answers (3)

b10n
b10n

Reputation: 1186

The translate method is my preferred way of doing this. Create a mapping between the chars you want mapped and then apply that table to your input string.

from string import maketrans

special = r"%.,-();'0123456789-—:`’" 
blanks = " " * len(special)
table = maketrans(special, blanks)
input_string.translate(table)

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can have a function with an optional fill value, if not set it will just delete/remove the non alpha characters or you can specify a default replace value:

def delete_replace(s,fill_char = ""):
    return "".join([x  if x.isalpha() else fill_char for x in s])

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

Seems like a good application for filter

>>> s = 'This is a test! It has #1234 and letters?'
>>> filter(lambda i: i.isalpha(), s)
'ThisisatestIthasandletters'

Upvotes: 0

Related Questions