latexlistings

Symbols replaced with not working ones into Python codes written via lstlisting Latex


lstlisting looks working great on python scripts except for some signs. From my experience the symbols "-" and "*" are replaced with something else, very similar in shape, but different. As a result the script reported into the pdf file doesn't work. That's the problem we are dealing with.

Here a simple sample code we gonna use in order to deal with this issue:

\documentclass{article}

\usepackage{listings}


\begin{document}
\lstset{language=Python}
\lstset{frame=lines}
\lstset{caption={Insert code directly in your document}}
\lstset{label={lst:code_direct}}
\lstset{basicstyle=\footnotesize}
%\lstset{keepspaces=true}
\lstset{columns=fullflexible}
\begin{lstlisting}
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.01)
y = np.sin(np.pi*x)/(np.pi*x)

plt.plot(x, y)
\end{lstlisting}


\end{document}

When I run it a pdf file is generated which looks great

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(−3, 3, 0.01)
y = np.sin(np.pi∗x)/(np.pi∗x)
plt.plot(x, y)

However, if I try to copy and paste this code on a Python intepreter I realize it does not work, as "*" and "-" are replaced with something else, very similar in shape, but different. Could you help me to fix it, please?


Solution

  • Not totally clear to me why this happens... can you add your preamble to the code? In particular, I am wondering what encoding (inutenc) you use.

    Not sure why listings behaves this way, but I found a literate option that allows specifying characters that should get replaced in the listing. In this case, I replace the minus with a minus, which seems to prevent some other code from replacing it with a different character. (I always got an equals sign.)

    This works for me:

    \documentclass{article}
    \usepackage[utf8]{inputenc}
    \usepackage{listings}
    \begin{document}
    
    \lstset{language=Python, literate={-}{-}1}
    \lstset{frame=lines}
    \lstset{caption={Insert code directly in your document}}
    \lstset{label={lst:code_direct}}
    \lstset{basicstyle=\footnotesize}
    \lstset{keepspaces=true}
    \lstset{columns=fullflexible}
    
    \begin{lstlisting}
    import numpy as np
    import matplotlib.pyplot as plt
    x = np.arange(-3, 3, 0.01)
    y = np.sin(np.pi*x)/(np.pi*x)
    
    plt.plot(x, y)
    \end{lstlisting}
    
    \end{document}
    

    Inspired by this question on tex.stackexchange.com.