[Tutor] wierd replace problem

Steven D'Aprano steve at pearwood.info
Tue Sep 14 00:41:28 CEST 2010


On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:

> How about using str.split() to put words in a list, then run strip()
> over each word with the required characters to be removed ('`")


Doesn't work. strip() only removes characters at the beginning and end 
of the word, not in the middle:


>>> "'I can't do this'".strip("'")
"I can't do this"

If the aim is to remove all quotation marks, replace() is the right way 
to go about it. It's not that hard either.

text = text.replace("'", "").replace('"', "").replace("`", "")

will remove all "standard" quotation marks, although if the source text 
contains non-English or unusual unicode quotes, you will need to do 
more work.

Or if you prefer something more easily extendable to other characters:

for c in "\"'`":
    text = text.replace(c, "")



-- 
Steven D'Aprano


More information about the Tutor mailing list