[Tutor] String punctuation

Blake Winton bwinton@tor.dhs.org
Fri, 26 Oct 2001 09:37:20 -0400


> This is probably what you wanted to get. But, to wet your appetite for
> more, here's some magic with the build in function 'filter'. This
> function does the same thing as the loop we've just written. Have a look
> at the Python documentation to see if you can fuigure out why this
> works.
> 
> >>> new_string = filter(is_not_punct_char, my_string)
> >>> new_string
> 'a string not too long containing  characters'

And, just cause I wanted a chance to play around with a new feature,
we can also write:

Python 2.2a3 (#1, Sep 16 2001, 12:18:17)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import string
>>> my_string = 'a string, not too long, containing "#$%&" characters.'
>>> "".join( [x for x in my_string if x not in string.punctuation] )
'a string not too long containing  characters'

But I'm not going to explain how this one works, other than to say
that I much prefer this version to the one using filter.  Well, okay
if you really want to know, email me, and I'll try to explain it in
a little more detail.

Later,
Blake.