0

I am seeing weird characters while using html text in python. Its just this one name which is inserting weird character ; into it.

My html text looks like this:

text="<font name=Helvetica color=white size=8>Name:  </font><font name=Helvetica-Bold color=white size=8>%s </font>" % name

where name = 'A&B CDE F.' But the output is: 'Name: A&B; CDE F.'

2
  • I cannot reproduce this behaviour. Can you add more context? Commented Jul 17, 2019 at 15:54
  • Hi! Sorry I did not give much info. I am using Paragraph from reportlab and using this text to draw on the PDF. Turtlefight's solution below solved my issue. Commented Jul 17, 2019 at 17:25

1 Answer 1

2

when interpolating variables into html strings / templates, you need to properly escape the string.

The Ampersand Character is used in html for character escapes, so you need to replace it with &amp;.

For Python 2 you can use cgi.escape:

import cgi
text="<font>%s</font>" % cgi.escape(name)

For Python 3 you can choose between cgi.escape and html.escape:

import html
text="<font>%s</font>" % html.escape(name)

Also check out the python wiki page for html escapes for a comprehensive overview of the different html escape functions in python :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.