[Tutor] Filtering a String

Archie Maskill galepsus at gmail.com
Sun Mar 20 23:45:40 CET 2005


On Sun, 20 Mar 2005 22:05:23 +0000, Matt Williams
<matthew.williams at cancer.org.uk> wrote:
> I've tried:
> 
> #!/usr/bin/python
> import string
> test="1,2,3,bob,%,)"
> allchar=string.maketrans('','')
> #This aiming to delete the % and ):
> x=''.translate(test,allchar,"%,)")
> 
> but get:
> TypeError: translate expected at most 2 arguments, got 3

According to Python's builtin help on the translate string method :

>>> help(''.translate)

translate(...)
   S.translate(table [,deletechars]) -> string

   Return a copy of the string S, where all characters occurring
   in the optional argument deletechars are removed, and the
   remaining characters have been mapped through the given
   translation table, which must be a string of length 256.

So it was all ok up to the last line, where instead of :

x=''.translate(test,allchar,"%,)")

you want :

x = test.translate(allchar,"%,)")

This will get rid of the commas as well, which you don't mention in
the comment on the preceeding line, so it's possible you need this
instead :

x = test.translate(allchar,"%)")

- Archie


More information about the Tutor mailing list