String interpolation

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing[1] or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). The placeholder may be a variable name, or in some languages an arbitrary expression, in either case evaluated in the current context.

String interpolation is an alternative to building string via concatenation, which requires repeat quoting and unquoting;[2] or substituting into a printf format string, where the variable is far from where it is used. Compare:

apples = 4
puts "I have #{apples} apples." # string interpolation
puts "I have " + String(apples) + " apples." # string concatenation
puts "I have %d apples." % apples # format string

Two types of literal expression are usually offered: one with interpolation enabled, the other without. Non-interpolated strings may also escape sequences, in which case they are termed a raw string, though in other cases this is separate, yielding three classes of raw string, non-interpolated (but escaped) string, interpolated (and escaped) string. For example, in Unix shells, single-quoted strings are raw, while double-quoted strings are interpolated. Placeholders are usually represented by a bare or a named sigil (typically $ or %), e.g. $apples or %apples, or with braces, e.g. {apples}, sometimes both, e.g. ${apples}. In some cases additional formatting specifiers can be used (as in printf), e.g. {apples:3}, and in some cases the formatting specifiers themselves can be interpolated, e.g. {apples:width}. Expansion of the string usually occurs at run time.

Language support for string interpolation varies widely. Some languages do not offer string interpolation, instead using concatenation, simple formatting functions, or template libraries. String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.

  1. ^ "Enforcing Strict Model-View Separation in Template Engines", T. Parr (2004), WWW2004 conference.
  2. ^ "Interpolation in Perl". This is much tidier than repeat uses of the '.' concatenation operator.