How to replace characters in a string?

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


Hi,

I misunderstood how it worked, basically I’ve added this function:

def filterCommonCharacters(theString):

    myNewString = theString.replace("\u2019", "'")

    return myNewString
Which returns a new string replacing the common characters.

This can easily be extended to include other characters as and when they come up by adding a line as so:

    myNewString = theString.replace("\u2014", “]”  #just an example

Which is what I was trying to achieve.

All the Best
Dave

> On 8 Jun 2022, at 11:17, Chris Angelico <rosuav at gmail.com> wrote:
> 
> On Wed, 8 Jun 2022 at 19:13, Dave <dave at looktowindward.com> wrote:
>> 
>> 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?
>> 
> 
> Not sure why you're passing the string as an argument as well as using
> it as the object you're calling a method on. All you should need to do
> is:
> 
> myString.replace('e', 'a')
> 
> ChrisA
> -- 
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list