[Tutor] String punctuation

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 26 Oct 2001 08:35:15 +0200


On  0, Mike Yuen <mjyuen@hotmail.com> wrote:
> Hi, i'm trying to figure how the string function punctuation works.  I'm 
> hoping that it will remove comma's, periods and other stuff from my strings.

Hi. string.punctuation is not a function, it's a string containing
punctuation:

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

> For some reason, I keep getting an attribute error.  Can anyone  tell me how 
> to use this?  Speak to me like i'm a 10 year old. I'm very new at this 
> stuff.

I'll show the simplest way then. If we have a string s, and we want to
remove all the characters that are in string.punctuation from it, one way
is to go through each of the characters in string.punctuation in turn, and
remove it from the string. You can remove characters by replacing them with
the empty string. So:

import string

def delete_punctuation(s):
    for char in string.punctuation:
    	s = string.replace(s, char, '')
    return s


print delete_punctuation("It's *not* 'you're' party, that's a 'typo'.")
# prints
# Its not youre party thats a typo

-- 
Remco Gerlich