You can try to use verbatim mode, i.e. \verb!my_name!
-- this is output always as \texttt
or use xparse
and define a command with verbatim argument 'v', but this macro can't be used in another macro.
This works with spaces too.
Note: The \begingroup...\endgroup
is to prevent the leaking of \ttfamily
to the following text.
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\mycommand}{+v}{%
\begingroup
\ttfamily #1%
\endgroup
}
\begin{document}
\verb!my_variable_name!
\mycommand{my_variable_name}
\end{document}
\verb!my_variable_name!
does the same ;-)\mycommand
? Or just strings of plain characters and_
?