Prepare accented characters for HTML

Tony van der Hoff lists at vanderhoff.org
Thu Mar 28 07:50:27 EDT 2019


On 28/03/2019 10:19, Antoon Pardon wrote:
> On 28/03/19 10:38, Tony van der Hoff wrote:
>> Hi,
>>
>> I have a MariaDB database, which contains accented (mostly French)
>> characters. I need to display these on an HTML page. I'm using the Jinja
>> templating engine.
>>
>> So, for instance, é needs to be replaced by é and so on. I've had
>> some success using string.replace(), but it is difficult to cater for
>> every case.
> 
> How about this function (python3):
> 
> def char2html(l):
>     return '&#%d;' % ord(l)
> 

Thanks, that'll work, but it's a bit of a pain examining every character
in the long (unicode?) string, and replacing it if necessary.

Meanwhile, by trial-and-error, I've found this workaround (maybe there's
a better way):

>>>'année'.encode(encoding='ascii',errors='xmlcharrefreplace').decode('ascii')
'année'


-- 
Tony van der Hoff        | mailto:tony at vanderhoff.org
Buckinghamshire, England |



More information about the Python-list mailing list