Programming Search⌘K

Conceptintro

String interpolation

Also called interpolation, variable interpolation, variable substitution, variable expansion, f-string, formatted string literal, template literal, template string, interpolated string, string template, ${}, $"".

String interpolation puts the values of variables or expressions into a string literal at the places of placeholders. f-strings, template literals and $"..." strings are examples.

Applies to
core-languages

Idea

A program often builds text from values: a message with a name, a line with a count, a path with a number. String interpolation puts the values into the text where they belong. "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"1.

In Python, an f-string has the prefix f, and each placeholder is an expression in braces:

name = "Ada"
count = 3
print(f"{name} has {count} new messages.")
print(f"Next week {name} has {count * 2}.")
print("{name} has {count}.")
Output
Ada has 3 new messages.
Next week Ada has 6.
{name} has {count}.

The first two strings get the values of name, count and count * 2. The third string has no prefix f, so the braces are only text. "String interpolation is an alternative to building a string via concatenation, which requires repeat quoting and unquoting"1: name + ' has ' + str(count) + ' new messages.' gives the same text with more quotes and an explicit conversion.

How it works

A literal with placeholders. An interpolated string is a literal in the source code, with a mark that tells the compiler to look for placeholders. The mark is a prefix (f in Python, $ in C#), a different quote (the backtick in JavaScript), or the kind of quote (double quotes in a shell). "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}"1.

The compiler splits the literal. The compiler or the interpreter splits the literal into its text parts and its expressions. At run time, the program computes each expression, converts the value to text, and joins the parts. For Python, "an f-string is really an expression evaluated at run time, not a constant value"2. In C#, "the compiler replaces items with interpolation expressions by the string representations of the expression results"3. So interpolation is a short form for a concatenation or a call to a format function, and the result is an ordinary string.

Variables or expressions. In some languages a placeholder holds only a name, and in others it holds any expression. Python's f-strings "provide a way to embed expressions inside string literals, using a minimal syntax"2. JavaScript's ${...} and C#'s {...} also accept any expression. A Rust format string with a name such as {count} reads a variable: "If a named parameter does not appear in the argument list, format! will reference a variable with that name in the current scope"4. But a Rust placeholder cannot hold an expression such as count * 2. A shell expands $name and ${name}, and an arithmetic expansion $((...)) for numbers.

Format specifiers. Many languages accept a format after the expression, for example a width or the number of decimals: {price:.2f} in Python, {price:F2} in C# and {price:.2} in Rust. The page Format specifiers describes these mini-languages.

Literal braces. If braces mark a placeholder, a brace in the text needs an escape. In Python, "the correct way to have a literal brace appear in the resulting string value is to double the brace"2. C# is the same: to include a brace in the text, "use two braces"3, {{ or }}. In Rust, "the { character is escaped with {{ and the } character is escaped with }}"4. JavaScript needs no escape for braces, because a placeholder starts with ${. A $ before a brace needs a backslash: `\${x}`.

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaIdiom
CAbsent
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the template literals of JavaScript, with any expression in ${...}, and template literal types that build string types from other types. No example file exists.
GoIdiom
RustNative
KotlinNativeKotlin string templates take a name after $ or an expression in ${...}, in normal and multiline strings. No example file exists because kotlinc is not installed.
SQLIdiomStandard SQL has no string interpolation. A query joins strings with the operator || or a function such as CONCAT, and some databases add a format function. No example file exists.
BashNativeBash expands $name, ${name} and $((expression)) inside double quotes, and single quotes keep the text as it is. No example file exists.
PowerShellNativeA PowerShell string in double quotes is an expandable string, with $name and $(expression) inside, and a string in single quotes is literal. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no expressions. Template engines and frameworks add placeholders such as {{ name }} on top of HTML.
CSSDoes not applyCSS has no string interpolation. var() reads a custom property and calc() computes a length, but neither builds a string from values.
Regular expressionsDoes not applyA pattern has no values to put into text. A replacement string can refer to groups with $1 or \1, which is a related but different idea.
Language Verdict Mechanism
Python native f-strings: f"{name} has {count}", with any expression and an optional format
JavaScript native template literals: `${name} has ${count}`, and tagged templates
TypeScript native template literals, as in JavaScript, and template literal types
Java idiom no interpolation; String.format, "...".formatted(...) or +
Kotlin native string templates: "$name has ${count * 2}"
C# native interpolated strings: $"{name} has {count}", with a format after :
Go idiom no interpolation; fmt.Sprintf("%s has %d", name, count)
Rust native names in format strings: format!("{name} has {count}"); no expressions
C absent no interpolation; snprintf with a format string
C++ idiom no interpolation; std::format("{} has {}", name, count)
Bash native parameter expansion in double quotes: "$name has $count"
PowerShell native expandable strings: "$name has $($count * 2)"
SQL idiom no interpolation; the operator || or a function such as format in some databases
Regex n/a a pattern is not a string with values; replacement strings refer to groups such as $1
HTML n/a HTML has no expressions; template engines add them
CSS n/a no interpolation; var() and calc() compute values, but not strings

The examples show the languages with a native form, and the idioms of the others.

JavaScript. "Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates"5. A tag is a function that gets the text parts and the values separately, so "a tagged template literal may not result in a string"5.

Kotlin. "String templates let you embed variables and expressions directly inside a String literal. This process is called interpolation"6. $name takes a name, and ${...} takes an expression.

Bash. "Enclosing characters in double quotes" keeps most characters as they are, but $, the backquote and the backslash keep their special meaning7. So "$name" expands the variable, and '$name' in single quotes is the text $name.

Go and C. Go has no interpolation. Its package fmt "implements formatted I/O with functions analogous to C's printf and scanf"8, so fmt.Sprintf takes a format string and a list of values. C has only printf and snprintf.

PythonGitHub
name = "Ada"
price = 4.5
items = ["tea", "milk"]

print(f"{name} pays {price * 2:.2f} for {len(items)} items.")
print(f"{name!r} {items[0].upper()} {price = }")
print(f"{{name}} is not a placeholder, {{{name}}} is.")
width = 8
print(f"[{name:>{width}}]")
Output
Ada pays 9.00 for 2 items.
'Ada' TEA price = 4.5
{name} is not a placeholder, {Ada} is.
[     Ada]
  • Verdict: native. An f-string accepts any expression in braces, a conversion such as !r after it, and a format after :. {price = } prints the expression, the sign = and the value, which helps in debug output. Two braces give one literal brace, and a format can contain a nested placeholder, such as the width {width}.
#include <format>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string name = "Ada";
    double price = 4.5;
    std::vector<std::string> items{"tea", "milk"};

    std::string s = std::format("{} pays {:.2f} for {} items.", name, price * 2, items.size());
    std::cout << s << '\n';
    std::cout << std::format("[{0:>6}] [{0:<6}] [{0}]", name) << '\n';
    std::cout << std::format("{{name}} is text, {{{}}} is not.", name) << '\n';
}
Output
Ada pays 9.00 for 2 items.
[   Ada] [Ada   ] [Ada]
{name} is text, {Ada} is not.
  • Verdict: idiom. C++ has no string interpolation. std::format takes a format string with braces and the values after it, and the compiler checks the format string against the types of the values. Braces can hold an index and a format, and two braces give one brace.
JavaGitHub
import java.util.List;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String name = "Ada";
        double price = 4.5;
        List<String> items = List.of("tea", "milk");

        System.out.println(String.format(Locale.ROOT, "%s pays %.2f for %d items.", name, price * 2, items.size()));
        System.out.println("%s has %d items.".formatted(name, items.size()));
        System.out.println(name + " pays " + price * 2 + " for " + items.size() + " items.");
        System.out.println("{name} and ${name} are text.");
    }
}
Output
Ada pays 9.00 for 2 items.
Ada has 2 items.
Ada pays 9.0 for 2 items.
{name} and ${name} are text.
  • Verdict: idiom. Java has no string interpolation, so braces and ${...} in a string literal are text. String.format and the method formatted take a format string with %s, %d and %.2f and the values after it. The operator + joins strings and converts the other values with their default text, so 9.0 has no format.
#include <stdio.h>

int main(void) {
    const char *name = "Ada";
    double price = 4.5;
    int count = 2;

    char buf[64];
    int n = snprintf(buf, sizeof buf, "%s pays %.2f for %d items.", name, price * 2, count);
    printf("%s (%d characters)\n", buf, n);

    char small[8];
    n = snprintf(small, sizeof small, "%s pays %.2f", name, price * 2);
    printf("[%s] needs %d characters\n", small, n);
    return 0;
}
Output
Ada pays 9.00 for 2 items. (26 characters)
[Ada pay] needs 13 characters
  • Verdict: absent. C has no string interpolation. snprintf writes the formatted text into a buffer of a given size, and it returns the length of the full text. If the buffer is too small, the text is cut, and the return value shows the size that the program needs.
using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string name = "Ada";
double price = 4.5;
string[] items = { "tea", "milk" };

Console.WriteLine($"{name} pays {price * 2:F2} for {items.Length} items.");
Console.WriteLine($"[{name,6}] [{name,-6}]");
Console.WriteLine($"{{name}} is text, {{{name}}} is not.");
Console.WriteLine($$"""{"name": "{{name}}"}""");
FormattableString f = $"{price:F1} and {items.Length}";
Console.WriteLine($"{f.Format} {f.ArgumentCount}");
Output
Ada pays 9.00 for 2 items.
[   Ada] [Ada   ]
{name} is text, {Ada} is not.
{"name": "Ada"}
{0:F1} and {1} 2
  • Verdict: native. A string with the prefix $ accepts any expression in braces, an alignment after a comma and a format after a colon. The conversion uses the current culture, so the program sets the invariant culture first. Two braces give one brace. In a raw string with $$, a placeholder needs two braces, so single braces are text, which helps for JSON. Assigned to FormattableString, the compiler keeps the composite format and the values apart.
JavaScriptGitHub
const name = "Ada";
const price = 4.5;
const items = ["tea", "milk"];

console.log(`${name} pays ${(price * 2).toFixed(2)} for ${items.length} items.`);
console.log(`Two lines:
${items.join(", ")}`);
console.log(`{name} and \${name} are text.`);

function tag(parts, ...values) {
  return parts.raw.join("|") + " / " + values.join("|");
}
console.log(tag`a${1}b${2}c`);
Output
Ada pays 9.00 for 2 items.
Two lines:
tea, milk
{name} and ${name} are text.
a|b|c / 1|2
  • Verdict: native. A template literal in backticks accepts any expression in ${...}, and it can span lines. There is no format part, so the code calls a method such as toFixed for the decimals. A brace alone is text, and \${ gives the text ${. A tag function receives the text parts and the values separately and returns any value.
package main

import (
	"fmt"
	"strconv"
)

func main() {
	name := "Ada"
	price := 4.5
	items := []string{"tea", "milk"}

	s := fmt.Sprintf("%s pays %.2f for %d items.", name, price*2, len(items))
	fmt.Println(s)
	fmt.Println(name + " has " + strconv.Itoa(len(items)) + " items.")
	fmt.Printf("%[1]s and %[1]q\n", name)
	fmt.Println("{name} and ${name} are text.")
}
Output
Ada pays 9.00 for 2 items.
Ada has 2 items.
Ada and "Ada"
{name} and ${name} are text.
  • Verdict: idiom. Go has no string interpolation. fmt.Sprintf takes a format string with verbs such as %s, %d and %.2f, and the values after it. The operator + joins strings only, so a number goes through strconv first. %[1]s takes the first value again.
RustGitHub
fn main() {
    let name = "Ada";
    let price = 4.5_f64;
    let items = ["tea", "milk"];

    let total = price * 2.0;
    let n = items.len();
    println!("{name} pays {total:.2} for {n} items.");
    println!("{} pays {:.2} for {} items.", name, price * 2.0, items.len());
    println!("[{name:>6}] [{name:<6}]");
    println!("{{name}} is text, {{{name}}} is not.");
    let s = format!("{name}-{n}");
    println!("{s}");
}
Output
Ada pays 9.00 for 2 items.
Ada pays 9.00 for 2 items.
[   Ada] [Ada   ]
{name} is text, {Ada} is not.
Ada-2
  • Verdict: native. A name in braces in the format string of println! or format! reads the variable with that name, and a format can follow after :. A placeholder holds only a name, not an expression, so the program puts price * 2.0 in a variable first or passes it as an argument. The macro checks the format string at compile time, and two braces give one brace.
  • Format functions. printf, String.format, str.format and std::format take a format string and the values separately. The format string can come from a file or a translation, which interpolation cannot do. See Format specifiers.
  • Templates. A template engine fills a text that the program reads at run time, with names and loops. See Use a text template.
  • Tagged templates and custom handlers. A JavaScript tag function and a C# interpolated string handler receive the parts and the values before the join. A library uses them to escape values for SQL or HTML, or to skip the work when a log level is off.
  • Raw strings. "Two types of literal expression are usually offered: one with interpolation enabled, the other without"1. For example, "in Unix shells, single-quoted strings are raw, while double-quoted strings are interpolated"1.

Pitfalls

  • The prefix is missing. Without the prefix f or $, the braces are text. No error occurs, and the output contains {name}, as the third line of the idea example shows. JavaScript has the same trap with normal quotes:

This code runs but gives a wrong answer on purpose.

const name = "Ada";
console.log("Hello, ${name}!");
console.log(`Hello, ${name}!`);
Output
Hello, ${name}!
Hello, Ada!
  • Injection. "String interpolation, like string concatenation, may lead to security problems"1. A value from a user can contain SQL, HTML or shell syntax. Never interpolate such a value into a query or a command. Use parameters in a query, and an escaping template for HTML.
  • A shell splits an unquoted expansion. In Bash, $name outside quotes goes through word splitting and filename expansion. A value with spaces becomes several words. Write "$name".
  • Default formats. Each value goes through its default conversion to text. A float can show many digits, and an object can show a type name. Give a format, such as {price:.2f}, when the text is for people.
  • Interpolation is not a template. An interpolated string is source code, so its text cannot come from a configuration file or a translation catalog. Use a format function or a template for text that changes at run time.

Cost

Interpolation costs the same as the concatenation or the format call that it replaces: one conversion for each value and one new string. The compiler parses the literal once, at compile time, so there is no parse at run time. Some compilers do better: C# interpolated string handlers write the parts into one buffer, and a Rust format string is checked at compile time.

History

Shells and scripting languages had interpolation first, and the idea spread to many languages: "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. Python added f-strings with PEP 498, created in August 2015, for Python 3.62. JavaScript template literals have been "available across browsers since September 2015"5.

References

  1. String interpolation, Wikipedia, Introduction; Security issues
  2. PEP 498, Literal String Interpolation, Abstract; Escape sequences
  3. String interpolation using $, C# language reference, Introduction; Special characters
  4. Module std::fmt, The Rust Standard Library, Named parameters; Escaping
  5. Template literals, MDN Web Docs, Introduction; Tagged templates
  6. Strings, Kotlin documentation, String templates
  7. Double Quotes, Bash Reference Manual, 3.1.2.3
  8. Package fmt, The Go Standard Library, Overview

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/AMEA3V/text.yaml