[Tex/LaTex] Color coding in Python f-strings

listingspythonstrings

Since Python 3.6, released Dec 2016, there is new f-string formatting, where, inside your string you can put python code to be evaluated in {}s. It's fantastic but TeX packages for code listings with syntax highlighting don't know about it, or do they?

MWE:

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\definecolor{cCodeString}{RGB}{42,0.0,255}
\definecolor{cCodeKeywordstyle}{RGB}{150,0,150}
\definecolor{cCodeComment}{RGB}{63,127,95}

\lstset{language=python,
    columns=fullflexible,
    basicstyle=\small\ttfamily,
    keywordstyle=\color{cCodeKeywordstyle}\bfseries,
    commentstyle=\color{cCodeComment},
    stringstyle=\color{cCodeString},
}

\begin{document}

\begin{lstlisting}
name = "Ann"
print(f"{name}, you have {len(name):4} characters in your name.")
\end{lstlisting}

\end{document}

enter image description here

It would be so good if the stuff inside the {} looked like code because the interpreter sees it as code.

Best Answer

I couldn't find an answer using the listings package.

However, I reckon the minted package understands Python f-strings:

\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{python}
  name = "Ann"
  print(f"{name}, you have {len(name)} characters in your name.")
\end{minted}
\end{document}

which renders as:

enter image description here

Note, however, that while LaTeX's minted package detects the first variable ({name}), it fails to detect the second one ({len(name)}).

This is actually a problem not of the minted package but of the Pygments Python lexer, as the pygmentize CLI renders it identically. (The minted package uses Pygments as its backend.)

I haven't found any solution to this problem yet, but have created an issue at the Pygment's GitHub repo.