How to replace characters in a string?

Roel Schroeven roel at roelschroeven.net
Wed Jun 8 07:37:46 EDT 2022


Op 8/06/2022 om 11:25 schreef Dave:
> 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.
When you have multiple replacements to do, there's an alternative for 
multiple replace calls: you can use theString.translate() with a 
translation map (which you can make yourself or make with 
str.maketrans()) to do all the replacements at once. Example

     # Make a map that translates every character from the first string 
to the
     # corresponding character in the second string
     translation_map = str.maketrans("\u2019\u2014", "']")

     # All the replacements in one go
     myNewString = theString.translate(translation_map)

See:
     - https://docs.python.org/3.10/library/stdtypes.html#str.maketrans
     - https://docs.python.org/3.10/library/stdtypes.html#str.translate

-- 

"There is a theory which states that if ever anyone discovers exactly what the
Universe is for and why it is here, it will instantly disappear and be
replaced by something even more bizarre and inexplicable.
There is another theory which states that this has already happened."
         -- Douglas Adams, The Restaurant at the End of the Universe



More information about the Python-list mailing list