2

I want to use lstlisting for some Python code, and I have a code segment that looks like this:

\documentclass[11pt]{article}

\usepackage{color}
\usepackage{listings}
\lstloadlanguages{Python}
\lstset{
  language=Python,
  basicstyle=\scriptsize\sffamily,
  numberstyle=\color{gray},
  stringstyle=\color[HTML]{933797}
  commentstyle=\color[HTML]{228B22}\sfffamily,
  emph={[2]from,import,pass,return}, emphstyle={[2]\color[HTML]{DD52F0}},
  emph={[3]range}, emphstyle={[3]\color[HTML]{D17032}},
  emph={[4]for,in,def}, emphstyle={[4]\color{blue}},
  showstringspaces=false,
  breaklines=true,
  prebreak=\mbox{{\color{gray}\tiny$\searrow$}},
  numbers=left,
  xleftmargin=15pt
}

\begin{document}
\begin{lstlisting}[language=Python]
# Function definitions

# Test cases
for _ in range(100):
    # Test comment
\end{lstlisting}

\end{document}

But the comments that start with # are not highlight with my specified color, they are just black. Any ideas?

5

There are three issues here: (1) gray is not defined by default in color, generally use xcolor instead. (2) there is a comma missing after stringstyle=\color[HTML]{933797}. (3) one too many f's in \sfffamily

Then the example works for me

Updated MWE:

\documentclass[11pt]{article}

\usepackage{xcolor}
\usepackage{listings}
\lstloadlanguages{Python}
\lstset{
  language=Python,
  basicstyle=\scriptsize\sffamily,
  numberstyle=\color{gray},
  stringstyle=\color[HTML]{933797},
  commentstyle=\color[HTML]{228B22}\sffamily,
  emph={[2]from,import,pass,return}, emphstyle={[2]\color[HTML]{DD52F0}},
  emph={[3]range}, emphstyle={[3]\color[HTML]{D17032}},
  emph={[4]for,in,def}, emphstyle={[4]\color{blue}},
  showstringspaces=false,
  breaklines=true,
  prebreak=\mbox{{\color{gray}\tiny$\searrow$}},
  numbers=left,
  xleftmargin=15pt
}

\begin{document}
\begin{lstlisting}[language=Python]
# Function definitions

# Test cases
for _ in range(100):
    # Test comment
\end{lstlisting}

\end{document}

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.