How to replace characters in a string?

Dave dave at looktowindward.com
Wed Jun 8 05:09:05 EDT 2022


Hi,

Thanks for this! 

So, is there a copy function/method that returns a MutableString like in objective-C? I’ve solved this problems before in a number of languages like Objective-C and AppleScript.

Basically there is a set of common characters that need “normalizing” and I have a method that replaces them in a string, so:

myString = [myString normalizeCharacters];

Would return a new string with all the “common” replacements applied.

Since the following gives an error :

myString = 'Hello'
myNewstring = myString.replace(myString,'e','a’)

TypeError: 'str' object cannot be interpreted as an integer

I can’t see of a way to do this in Python? 

All the Best
Dave


> On 8 Jun 2022, at 10:14, Chris Angelico <rosuav at gmail.com> wrote:
> 
> 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
> -- 
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list