Matt Williams wrote:
Dear List,

I'm trying to filter a file, to get rid of some characters I don't want
in it.

I've got the "Python Cookbook", which handily seems to do what I want,
but:

a) doesn't quite and b) I don't understand it

I'm trying to use the string.maketrans() and string.translate(). From
what I've read (in the book and the Python Docs), I need to make a
translation table, (using maketrans) and then pass the table, plus and
optional set of characters to be deleted, to the translate() function.

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

Please could someone explain this to me (slowly).

Here is an updated version.

#!/usr/bin/python

import string

test = "1,2,3,bob,%,)"
allchar = string.maketrans('','')
#This aiming to delete the % and ):



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

print x
# end

x = test.translate() rather than x = ''.translate() is the key. You want to call the translate method of the test string. Your code could have worked by doing 'x = string.translate(test, allchar, "blah")' which uses the translate function in the module named 'string'. Confusing because the names are the same.

You received an error because ''.translate() only needs the table and the deletechars string. I personally avoid empty string methods (''.translate, ''.join, etc) because they can be visually confusing and definitely confound the new python programmers.

A comment on style. Use spaces around assignments -- x=5 should be x = 5.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to