fra fra - 2 years ago 244
Python Question

Python TypeError using the translate() method

I am trying to build a function in Python that pulls specific characters out of a string, and then returns each of the remaining words on a separate line. Apostrophes must be removed -- and the contraction must be split, with the second half moving to a new line.

For instance, I have this sentence fragment:

", that doesn't mean much to him."

And I want to remove these punctuation characters:


It should return:


Here is the function I've written:

def remove_chars(frag, punc):
if "'" in frag:
frag = frag.replace("'", " ")

frag = frag.translate(None, punc)

frag = frag.split(" ")

for i in frag:
print i

remove_chars(", that doesn't mean much to him.", ",'.")

And here's the error I'm receiving:

TypeError: deletions are implemented differently for unicode

Thanks in advance for any help with this.

fra fra
Answer Source

I did a whole lot more research, and I finally came up with this -- which I think is correct (and probably the cleanest solution):

def remove_chars(frag, punc):

    for i in punc:
        frag = frag.replace(i, ' ')
    for j in frag.split():
        print j

print remove_chars(", that doesn't mean much to him.", ",'.")

If you see a mistake, please let me know.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download