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:- 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.
- 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 (XXE) 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|.
I have 4 apples
Bash
apples=4
echo "I have $apples apples"
- or
The output will be:
Boo
apples = 4
- or
The output will be:
C
C does not have interpolated strings, but they can be approximated usingsprintf from .- include
- define BUFFER_SIZE 100
C++
While interpolated strings do not exist in C++, they can be approximated usingstd::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
ColdFusion Markup Language script syntax:apples = 4;
writeOutput;
Tag syntax:
The output will be:
CoffeeScript
apples = 4
console.log "I have # apples"
The output will be:
Dart
int apples = 4, bananas = 3;
print;
print;
The output will be:
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:
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
JavaScript 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
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:
Console.WriteLine;
The output will be:
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"
- Multi-line
I have
apples"""
- Debug the formatting
- Custom openChar and closeChar characters
- Backslash inside the formatted string literal
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
Nix
let numberOfApples = "4";
in "I have $ apples"
The output will be:
I have 4 apples
ParaSail
const Apples := 4
const Bananas := 3
Println
Println
The output will be:
I have 4 apples.
I have 7 fruits.
Perl
my $apples = 4;
my $bananas = 3;
print "I have $apples apples.\n";
print "I have @ fruit.\n"; # Uses the Perl array interpolation.
The output will be:
I have 4 apples.
I have 7 fruit.
PHP
$apples = 5;
$bananas = 3;
echo "There are $apples apples and $bananas bananas.\n";
echo "I have apples and bananas.";
I have 5 apples and 3 bananas.
Python
Python supports string interpolation as of version 3.6, referred to as"formatted string literals" or "f-strings". Such a literal begins with an
f or F before the opening quote, and uses braces for placeholders:apples: int = 4
bananas: int = 3
The output will be:
I have 4 apples and 3 bananas
Ruby/Crystal
apples = 4
puts "I have # apples"
- Format string applications for comparison:
puts "I have % apples" %
The output will be:
Rust
Rust does not have general string interpolation, but provides similar functionality via macros, referred to as "Captured identifiers in format strings", introduced in version 1.58.0, released 2022-01-13.Rust provides formatting via the module, which is interfaced with through various macros such as,, and . These macros are converted into Rust source code at compile-time, whereby each argument interacts with a . The formatter supports,,, defining various, and capturing identifiers from the environment.
fn main
The output will be:
There are 4 apples and 3 bananas.
Scala
Scala 2.10+ provides a general facility to allow arbitrary processing of a string literal, and supports string interpolation using the includeds and f string interpolators. It is also possible to write custom ones or override the standard ones.The
f interpolator is a compiler macro that rewrites a format string with embedded expressions as an invocation of String.format. It verifies that the format string is well-formed and well-typed.The standard interpolators
Scala 2.10+'s string interpolation allows embedding variable references directly in processed string literals. Here is an example:val apples = 4
val bananas = 3
//before Scala 2.10
printf
println
//Scala 2.10+
println
println
println
The output will be:
Sciter (tiscript)
In Sciter any function with name starting from $ is considered as interpolating function and so interpolation is customizable and context sensitive:var apples = 4
var bananas = 3
var domElement =...;
domElement.$content;
domElement.$append;
Where
I have " + apples.toHtmlString + " apples
";Snobol
apples = 4 ; bananas = 3
Output = "I have " apples " apples."
Output = "I have " " fruits."
The output will be:
I have 4 apples.
I have 7 fruits.
Swift
In Swift, a new String value can be created from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item inserted into the string literal is wrapped in a pair of parentheses, prefixed by a backslash.let apples = 4
Tcl
The Tool Command Language has always supported string interpolation in all quote-delimited strings.set apples 4
puts "I have $apples apples."
The output will be:
In order to actually format – and not simply replace – the values, there is a formatting function.
set apples 4
puts
Visual Basic .NET
As of Visual Basic 14, string interpolation is supported in Visual Basic.name = "Tom"
Console.WriteLine
The output will be: