How to replace characters in a string?
Joel Goldstick
joel.goldstick at gmail.com
Wed Jun 8 05:26:09 EDT 2022
On Wed, Jun 8, 2022 at 5:22 AM Karsten Hilbert <Karsten.Hilbert at gmx.net> wrote:
>
> Am Wed, Jun 08, 2022 at 11:09:05AM +0200 schrieb Dave:
>
> > myString = 'Hello'
> > myNewstring = myString.replace(myString,'e','a’)
>
> That won't work (last quote) but apart from that:
>
> myNewstring = myString.replace('e', 'a')
>
> Karsten
> --
> GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B
> --
> https://mail.python.org/mailman/listinfo/python-list
Sorry if I'm not reading the nuances correctly, but it looks to me
that you failed to realize that string methods return results. They
don't change the string in place:
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str1 = "\u2019string with starting smart quote"
>>> str1
'’string with starting smart quote'
>>> new_str = str1.replace("\u2019","'")
>>> str1
'’string with starting smart quote'
>>> new_str
"'string with starting smart quote"
>>> repr(str1)
"'’string with starting smart quote'"
>>> repr(new_str)
'"\'string with starting smart quote"'
>>>
As you can see, str1 doesn't change, but when you 'replace' on it, the
result you want is returned to new_str
--
Joel Goldstick
More information about the Python-list
mailing list