Mainland
Mainland

Reputation: 4564

Python printing & (and) character in MS word through python

I am generating MS word files through Python using docxtpl. I am trying to import the Humanities&Social Sciences text into an MS word file. But, I see Humanities Sciences printed in MS word.

I tried these combinations, but they did not work: Humanities&&Social Sciences, Humanities\&Social Sciences. What should I write in python so that when I import it into MS word, I see the full and complete text?

Upvotes: 0

Views: 329

Answers (1)

Hasidul Islam
Hasidul Islam

Reputation: 416

How Escaping works in docxtpl is given below. Following this will solve your issue.

By default, no escaping is done.

When you use a {{ }}, under the hood, you are modifying an XML word document, this means you cannot use all chars, especially <, > and &. In order to use them, you must escape them. There are 4 ways :

    context = { 'var':R('my text') } and {{r <var> }} in the template (note the r),
    context = { 'var':'my text'} and {{ <var>|e }} in your word template
    context = { 'var':escape('my text')} and {{ <var> }} in the template.
    enable autoescaping when calling render method: tpl.render(context, autoescape=True) (default is autoescape=False)

See tests/escape.py example for more informations.

Another solution, if you want to include a listing into your document, that is to escape the text and manage \n, \a, and \f you can use the Listing class

in your python code:

context = { 'mylisting':Listing('the listing\nwith\nsome\nlines \a and some paragraph \a and special chars : <>&') }

in your docx template just use {{ mylisting }}

With Listing(), you will keep the current character styling (except after a \a as you start a new paragraph).

Upvotes: 1

Related Questions