String interpolation


In computer programming, string interpolation 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 or, in formal terms, a form of quasi-quotation. 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 a string via concatenation, which requires repeat quoting and unquoting; or substituting into a printf format string, where the variable is far from where it is used. Consider this example in Ruby:

apples = 4
puts "I have # apples." # string interpolation
puts "I have " + String + " 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 string, interpolated 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, e.g. $apples or %apples, or with braces, e.g. , sometimes both, e.g. $. In some cases, additional formatting specifiers can be used, e.g. , and in some cases the formatting specifiers themselves can be interpolated, e.g. . 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.

Algorithms

There are two main types of variable-expanding algorithms for variable interpolation:
  1. Replace and expand placeholders: creating a new string from the original one, by find–replace operations. Find variable reference, replace it with its variable value. This algorithm offers no cache strategy.
  2. Split and join string: splitting the string into an array, merging it with the corresponding array of values, then joining items by concatenation. The split string can be cached for reuse.

    Security issues

String interpolation, like string concatenation, may lead to security problems. If user input data is improperly escaped or filtered, the system will be exposed to SQL injection, script injection, XML external entity injection, and cross-site scripting attacks.
An SQL injection example:
query = " "
If $id is replaced with "'; ", executing this query will wipe out all the data in Table.

Examples

ABAP


DATA = 4.
WRITE |I have apples|.
The output will be:
I have 4 apples

Bash


apples=4
echo "I have $apples apples"
  1. or
echo "I have $ apples"

The output will be:
I have 4 apples

Boo


apples = 4
print
  1. or
print

The output will be:
I have 4 apples

C

C does not have interpolated strings, but they can be approximated using sprintf from .

  1. include
  2. define BUFFER_SIZE 100
int main

C++

While interpolated strings do not exist in C++, they can be approximated using std::format and std::print functions.

import std;
using std::string;
int main

Interpolated strings have been proposed for inclusion into C++, based on Python f-strings. The proposal incorporates features previously included from std::format, based on fmtlib. In this proposal, each f-string is transformed into a function call to a new function, std::make_formatted_string.

import std;
using std::string;
using std::string_view;
int calculate
string represent
void display

C#


namespace Wikipeda.Examples;
public class Example

The output will be:

I have 4 apples
I have 7 fruits

This can also be done using String.Format.

namespace Wikipedia.Examples;
using System;
public class Example

ColdFusion Markup Language

script syntax:

apples = 4;
writeOutput;

Tag syntax:


I have #apples# apples

The output will be:

CoffeeScript


apples = 4
console.log "I have # apples"

The output will be:
I have 4 apples

Dart


int apples = 4, bananas = 3;
print;
print;

The output will be:
I have 4 apples.
I have 7 fruits.

Go

While there have been some proposals for string interpolation, Go does not have interpolated strings.
However, they can be approximated using fmt.Sprintf.

import "fmt"
func main

Groovy

In groovy, interpolated strings are known as GStrings:

def quality = "superhero"
final age = 52
def sentence = "A developer is a $quality if he is $"
println sentence

The output will be:
A developer is a superhero if he is seasoned

Haxe


var apples = 4;
var bananas = 3;
trace;
trace;

The output will be:

I have 4 apples.
I have 7 fruits.

Java

Java had interpolated strings as a preview feature in Java 21 and Java 22. One could use the constant STR of directly.

package org.wikipedia.examples;
enum Stage
record Deploy
public class Example

They were removed in Java 23 due to design issues.
Otherwise, interpolated strings can be approximated using the String.format method.

package org.wikipedia.examples;
public class Example

JavaScript/TypeScript

and TypeScript, as of the ECMAScript 2015 standard, support string interpolation using backticks ``. This feature is called template literals. Here is an example:

const apples: number = 4;
const bananas: number = 3;
console.log;
console.log;

The output will be:

I have 4 apples
I have 7 fruits

Template literals can also be used for multi-line strings:

console.log;

The output will be:

This is the first line of text.
This is the second line of text.

Julia


apples = 4
bananas = 3
print

The output will be:

I have 4 apples and 3 bananas, making 7 pieces of fruit in total.

Kotlin


fun main

The output will be:

A developer is a superhero. I have 7 fruits

Nemerle


def apples = 4;
def bananas = 3;
Console.WriteLine;
Console.WriteLine;

It also supports advanced formatting features, such as:
def fruit = ;
Console.WriteLine;

The output will be:
apples
bananas

Nim

Nim provides string interpolation via the strutils module.
Formatted string literals inspired by Python F-string are provided via the strformat module,
the strformat macro verifies that the format string is well-formed and well-typed,
and then are expanded into Nim source code at compile-time.

import strutils, strformat
var apples = 4
var bananas = 3
echo "I have $1 apples".format
echo fmt"I have apples"
echo fmt"I have fruits"
  1. Multi-line
echo fmt"""
I have
apples"""
  1. Debug the formatting
echo fmt"I have apples"
  1. Custom openChar and closeChar characters
echo fmt ", '
  1. Backslash inside the formatted string literal
echo fmt""""""

The output will be:

I have 4 apples
I have 4 apples
I have 7 fruits
I have
4 apples
I have apples=4 apples
I have 4
yep
ope