Skip to main content
  1. Posts/

Define A String Variable in LaTeX

·223 words·2 mins·
Table of Contents

Like other programming languages, the best way to to use a value multiple times in LaTeX is to define a variable for it. Later when you want to change the value, you only need to change it once. Here is how to do it.

Use \newcommand
#

We can use \newcommand to define a new command for the text like this:

\newcommand{\toyCommand}{some text}

In the main, to insert the text, we can call this command:

We can use \toyCommand{} like this.

Or we can use \toyCommand\ like this.

Note that the double bracket {} or escaped space \ after the custom command is necessary, without which, the inserted text and text after it will stick together with no space.

If we just want to use \toyCommand, we can use xspace package and add space when defining the command:

\usepackage{xspace}

\newcommand{\toyCommand}{some text\xspace}

Note that xspace do have some drawbacks, see discussion here.

Use \def
#

We can also use \def to define a variable and use it later1.

\def \myVar {some text}

We can use \myVar{} like this.

Note that {} is also required to add a literal sapce after the inserted text.

References
#


  1. It may override existing macro without warning, so use it with care. ↩︎

Related

Change Table Column Width in LaTeX
··664 words·4 mins
Image or Table Side by Side in LaTeX
··683 words·4 mins
Tips on Writing Papers in LaTeX
··292 words·2 mins