# Correctly typesetting words surrounded by double underscores?

Forgive me if the answer to this is obvious, I've just begun working with LaTex and I've had no luck with Google.

I'm working on learning LaTeX, and as part of my practice I'm rewriting a guide on special methods in Python in LaTeX. As you might know, Python's special methods take on the form __methodname__. This causes problems when I try to generate a PDF from my .tex source file using pdflatex. How can I make LaTeX ignore the double underscores, or otherwise make my output correct?

In case it might help, here's a sample of what I'm trying to typeset:

 e.g. \texttt{__init__} or \texttt{__lt__}


Which I want to look like "e.g. __init__ or __lt__".

-
–  Caramdir Mar 15 '11 at 4:46
@Caramdir somewhat. \usepackage{underscore} makes everything generate without error, but the underscores have a space between them, which looks ugly :( –  Rafe Kettler Mar 15 '11 at 5:07
When you are typesetting Python computer code it is important to show that it is two distinct underscores. "Ugly" is not the issue here, but clarity. –  Danie Els Mar 15 '11 at 5:31
@Danie the entire Python documentation (including that which is set with TeX) does not show two distinct underscores. It's fairly easy to distinguish between _ and __ especially in context. –  Rafe Kettler Mar 15 '11 at 5:37
It does not mean that the Python docs use good practices. I have many years of trying to teach engineering students programming and I can guarantee you, if there are ambiguities, it will cause problems. –  Danie Els Mar 15 '11 at 5:57

Use \texttt{\_\_init\_\_} or \verb+__init__+ or with the inline options of the listings package

\makeatletter
% Ensure that the minus sign is the "-" character in listings
% for cut and paste operations from pdf docs
\newcommand*\verbfont{%
\normalfont\ttfamily\hyphenchar\font\m@ne\@noligs}
\makeatother

\lstset{language         =Python,
showstringspaces =false,
keepspaces       =true,
basicstyle       = \raggedright\verbfont\small\selectfont}

\newcommand\li{%
\lstinline[basicstyle = \verbfont\raggedright]}


Then you can use \li{__init__}

-
Is there any advantage to any particular approach? \verb!__init__! seems easiest, but does it have some limitations? –  Rafe Kettler Mar 15 '11 at 5:47
@Rafe \verb can not be used in macro arguments such as \caption, etc. If it is a document about computer code go the listings way. It also gives a verbatim type environment for code listings with coloring and many other options. –  Danie Els Mar 15 '11 at 6:05
@Rafe: If you go for \verb note that there is the shortvrb package which allows you to say \MakeShortVerb{\|} and then |__init__| is enough. Works with any other character like ! as well. –  Martin Scharrer Mar 15 '11 at 8:45
@RafeKettler: You should probably accept this answer. –  strpeter Feb 13 '13 at 17:53