Skip to content Skip to sidebar Skip to footer

Replacing A Unicode Character In A String In Python 3

I have a string where some of the characters appear as unicode, e.g.: 'bla bla bla \uf604 bla bla bla' I tried doing string = string.replace('\uf604', 'X'), but nothing happens. I

Solution 1:

In Python 3, this works (although the print may not, depending on your terminal):

>>>s="bla bla bla \uf604 bla bla bla">>>print(s)
bla bla bla  bla bla bla
>>>s="bla bla bla \uf604 bla bla bla">>>s.replace('\uf604','X')
'bla bla bla X bla bla bla'

But perhaps you have a literal slash and not an escape code. Note the print difference:

>>>s="bla bla bla \\uf604 bla bla bla">>>print(s)
bla bla bla \uf604 bla bla bla
>>>s.replace('\uf604','X')
'bla bla bla \\uf604 bla bla bla'

Use a escape slash to fix:

>>> s.replace('\\uf604','X')
'bla bla bla X bla bla bla'

Post a Comment for "Replacing A Unicode Character In A String In Python 3"