How to replace characters in a string?

Chris Angelico rosuav at gmail.com
Wed Jun 8 04:14:46 EDT 2022


On Wed, 8 Jun 2022 at 18:12, Dave <dave at looktowindward.com> wrote:

> I tried the but it doesn’t seem to work?
> myCompareFile1 = ascii(myTitleName)
> myCompareFile1.replace("\u2019", "'")

Strings in Python are immutable. When you call ascii(), you get back a
new string, but it's one that has actual backslashes and such in it.
(You probably don't need this step, other than for debugging; check
the string by printing out the ASCII version of it, but stick to the
original for actual processing.) The same is true of the replace()
method; it doesn't change the string, it returns a new string.

>>> word = "spam"
>>> print(word.replace("sp", "h"))
ham
>>> print(word)
spam

ChrisA


More information about the Python-list mailing list