[Tutor] Filtering a String

Jacob S. keridee at jayco.net
Sun Mar 20 23:25:25 CET 2005


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

The easiest thing to do is use the string method replace.
For example:


char = "1"
a = open("Myfile.txt","r")
b = a.read()
a.close()

b = b.replace(char,"")
a = open("Myfile.txt","w")     ## Notice "w" so we can replace the file
a.write(b)
a.close

> 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 never messed with translate() etc...

> 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

Ah, your test uses more than one replace factor.
So, this should do what you want..

#####
x = " [ text ] "   # Replace this with your file output -- possibly 
fileobject.read()
def removechar(stri, char):
    return stri.replace(char,"")
test = "1,2,3,bob,%,)"
allchar = test.split(",")   # this makes allchar = 
['1','2','3','bob','%',')']
for char in allchar:
    x = removechar(x,char)
######

Remember, if you need help--just ask.
Oh, and don't give up hope!

HTH,
Jacob




More information about the Tutor mailing list