The str.translate() method accepts a table of codepoints (numerical value of a character) mapped to another character or codepoint. Map to None for characters that have to be deleted. You can use the ord() built-in function to get the codepoint of characters. Or, you can use the str.maketrans() method to generate the mapping for you.

>>> ord('a')
97
>>> ord('A')
65

>>> greeting = 'have a nice day'
# map 'a' to 'A', 'e' to 'E' and 'i' to None
>>> greeting.translate({97: 65, 101: 'E', 105: None})
'hAvE A ncE dAy'

# first and second arguments specify the one-to-one mapping of characters
# third argument is optional, specifies characters to be deleted
>>> str.maketrans('ae', 'AE', 'i')
{97: 65, 101: 69, 105: None}
>>> greeting.translate(str.maketrans('ae', 'AE', 'i'))
'hAvE A ncE dAy'

The string module has a collection of constants that are often useful in text processing. Here's an example of deleting punctuation characters:

>>> from string import punctuation
>>> punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

>>> para = '"Hi", there! How *are* you? All fine here.'
>>> para.translate(str.maketrans('', '', punctuation))
'Hi there How are you All fine here'

>>> chars_to_delete = ''.join(set(punctuation) - set('.!?'))
>>> para.translate(str.maketrans('', '', chars_to_delete))
'Hi there! How are you? All fine here.'

Video demo:


info See also my 100 Page Python Intro ebook.