3

I am trying to implement a python function (which processes text for me) in my tex document. Thus I started as following:
Tex:

%& -shell-escape
\documentclass{article}
\usepackage{pythontex}
\usepackage{lettrine}
\newcommand{\printPython}[1]{
\pyc{print(r'Hello #1')}%
}
\begin{document}

Say hello Python:

%\begin{python}%
%print r"Hello \LaTeX!"
%\end{python}%
\printPython{Test}

\begin{pycode}
from BigLet import *

a = modifyText("Hallo Welt")
print(r"\textit{\py{modifyText("HalloWelt")}}")
print(r"\newline")
print(r"\centering")
print(r"\textit{A message from Python!}")
\end{pycode}

\end{document}

BigLet.py:

from __future__ import division

def modifyText(inputstring):
    wordlist = inputstring.split(' ')
    chordItem = '\\'
    if chordItem not in wordlist[0]:
        firstWord = wordlist[0]
        firstLetter = firstWord[0]
        modWord = "\lettrine{"+firstLetter+"}{"+firstWord[1:]+'}'
        fullText = modWord + ' ' + inputstring[len(firstWord):]
        return fullText
    else:
        firstWord = wordlist[1]
        print firstWord
        firstLetter = firstWord[0]
        modWord = "\lettrine{"+firstLetter+"}{"+firstWord[1:]+'}'
        fullText = inputstring[:len(wordlist[0])] + ' ' + modWord + ' ' + inputstring[len(wordlist[0]) + len(firstWord):]
        return fullText

My problem is now that I can neither access the value of a (which is a string) nor use the line print(r"\textit{\py{modifyText("HalloWelt")}}"). When using the line, I get the error

print(r"\textit{\py{modifyText("HalloWelt")}}")
                                              ^
  SyntaxError: invalid syntax

When I am printing a by using print(r"\textit{a}"), I just get the letter a. When changing that line into print(r"\textit{\py{a}}"), I get two question marks. How can I access the resulting string from the external function, and pass it forward? Just printing works.

4

print(r"\textit{\py{modifyText("HalloWelt")}}") is giving a syntax error because you are trying to include unescaped literal double quotes within a double quote-delimited string. You would need something like print(r'\textit{\py{modifyText("HalloWelt")}}')

print(r"\textit{a}") is printing a string, so you just get the string.

You probably want something like print(r"\textit{" + a + "}") or perhaps print(r"\textit{{{a}}}".format(a=a)). Or you could avoid the temporary variable and use print(r"\textit{" + modifyText("Hallo Welt") + "}") There are almost no situations in which printing \py{...} is actually necessary. Typically, you can just assemble the final text, and then print that.

If you get two question marks, that is an indication that you need to run PythonTeX again, and then recompile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.