How to format LaTeX string in python?

I am writing an application, of which CVT LaTeX generation is part, so I am in a situation where I have lines like

\begin{document} \title{Papers by AUTHOR} \author{} \date{} \maketitle \begin{enumerate} %% LIST OF PAPERS %% Please comment out anything between here and the %% first \item %% Please send any updates or corrections to the list to %% XXXEMAIL???XXX %\usepackage[pdftex, ... 

which I would like to fill with dynamic information, for example. E-mail address. Due to the format of LaTeX itself ... the format with the {email} syntax will not work, and none of them will use the dictionary with the% (email) syntax. Editing: in particular, lines such as "\ begin {document}" (command in LaTeX) should be left literally as they are, without replacing with .format and lines such as "%%" (comment in LaTeX) should also be on the left, without replacing the dictionary. What is a smart way to do this?

+8
python string format latex
source share
2 answers

Why is this not working?

 >>> output = r'\author{{email}}'.format(email='user@example.org') >>> print output \author{email} 

edit: use double curly braces to escape literal curly braces that only LaTeX understands:

 >>> output = r'\begin{{document}} ... \author{{{email}}}'.format( ... email='user@example.org') >>> print output \begin{document} ... \author{user@example.org} 
+9
source share

You cannot use the new format syntax to avoid escaping { and } .

This should work:

 >>> a = r''' \title{%(title)s} \author{%(author)s} \begin{document}''' >>> b = a % {'title': 'My Title', 'author': 'Me, Of course'} >>> print(b) \title{My Title} \author{Me, Of course} \begin{document} 

You must use r'something' raw strings to avoid escaping \ like \\ .

PS: you should take a look at txt2tags , a Python script to convert t2t formatted text to html, latex, markdown, etc. Check the source code to find out how.

+2
source share

All Articles