In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a
string literal
A string literal or anonymous string is a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally " bracketed delimiters", as in x = "foo", where "foo" is a string ...
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 (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
Context may refer to:
* Context (language use), the relevant constraints of the communicative situation that influence language use, language variation, and discourse summary
Computing
* Context (computing), the virtual environment required to s ...
.
String interpolation is an alternative to building string via
concatenation
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenat ...
, which requires repeated quoting and unquoting; or substituting into a
printf format string
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
, where the variable is far from where it is used. Compare:
apples = 4
print("I have $ apples.") # string interpolation
print("I have " + apples + " apples.") # string concatenation
print("I have %s 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 sequence
In computer science, an escape sequence is a combination of characters that has a meaning other than the literal characters contained therein; it is marked by one or more preceding (and possibly terminating) characters.
Examples
* In C and ma ...
s, in which case they are termed a
raw string
A string literal or anonymous string is a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally " bracketed delimiters", as in x = "foo", where "foo" is a strin ...
, 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
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitio ...
(typically
$
or
%
), e.g.
$apples
or
%apples
, or with braces, e.g.
, sometimes both, e.g.
$
. In some cases additional formatting specifiers can be used (as in printf), 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 language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s which make heavy use of
string representations of data, such as
Apache Groovy,
Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e ...
,
Kotlin,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
,
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
,
Python,
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
,
Scala,
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT ...
,
Tcl and most
Unix shell
A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system t ...
s.
Algorithms
There are two main types of expand variable algorithms for ''variable interpolation'':
# ''Replace and expand placeholders'': creating a new string from the original one, by find-replace operations. Find variable-reference (placeholder), replace it by its variable-value. This algorithm offers no cache strategy.
# ''Split and join string'': splitting the string into an array, and merging it with the corresponding array of values; then join items by concatenation. The split string can be cached to 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
In computing, SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL inj ...
,
script injection,
XML External Entity Injection (XXE), and
cross-site scripting
Cross-site scripting (XSS) is a type of security vulnerability that can be found in some web applications. XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may ...
(XSS) 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(apples) = 4.
WRITE , I have apples, .
The output will be:
I have 4 apples
Bash
apples=4
echo "I have $apples apples"
# or
echo "I have $ apples"
The output will be:
I have 4 apples
Boo
apples = 4
print("I have $(apples) apples")
# or
print("I have apples" % apples)
The output will be:
I have 4 apples
C#
var apples = 4;
var bananas = 3;
Console.WriteLine($"I have apples");
Console.WriteLine($"I have fruits");
The output will be:
I have 4 apples
I have 7 fruits
ColdFusion Markup Language
ColdFusion Markup Language
ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availab ...
(CFML) script syntax:
apples = 4;
writeOutput("I have #apples# apples");
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('I have $apples apples.');
print('I have $ fruit.');
The output will be:
I have 4 apples.
I have 7 fruit.
Go
, Go does not have string interpolation. There have been some proposals for string interpolation in the next version of the language, Go 2. Instead, Go uses
printf format string
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
s in the
fmt.Sprintf
function, string
concatenation
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenat ...
, or template libraries like
text/template
.
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('I have $apples apples.');
trace('I have $ fruit.');
The output will be:
I have 4 apples.
I have 7 fruit.
Java
, Java does not have interpolated strings, and instead uses format functions, notably the
MessageFormat
class (Java version 1.1 and above) and the static method
String.format
(Java version 5 and above)
There is a proposalto add string interpolation to the Java language. This proposal aims at doing safe string interpolation, making it easier to prevent injection attacks.
JavaScript
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, as of the
ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scriptin ...
2015 (ES6) standard, supports string interpolation using backticks
``
. This feature is called ''template literals''. Here is an example:
const apples = 4;
const bananas = 3;
console.log(`I have $ apples`);
console.log(`I have $ fruit`);
The output will be:
I have 4 apples
I have 7 fruit
Template literals can also be used for multi-line strings:
console.log(`This is the first line of text.
This is the second line of text.`);
The output will be:
This is the first line of text.
This is the second line of text.
Julia
apples = 4
bananas = 3
print("I have $apples apples and $bananas bananas, making $(apples + bananas) pieces of fruit in total.")
The output will be:
I have 4 apples and 3 bananas, making 7 pieces of fruit in total.
Kotlin
val quality = "superhero"
val apples = 4
val bananas = 3
val sentence = "A developer is a $quality. I have $ fruit"
println(sentence)
The output will be:
A developer is a superhero. I have 7 fruit
Nemerle
def apples = 4;
def bananas = 3;
Console.WriteLine($"I have $apples apples.");
Console.WriteLine($"I have $(apples + bananas) fruit.");
It also supports advanced formatting features, such as:
def fruit = apple", "banana"
Console.WriteLine($<#I have ..$(fruit; "\n"; f => f + "s")#>);
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(apples)
echo fmt"I have apples"
echo fmt"I have fruits"
# Multi-line
echo fmt"""
I have
apples"""
# Debug the formatting
echo fmt"I have apples"
# Custom openChar and closeChar characters
echo fmt("I have (apples) ", '(', ')')
# 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
Nix
let numberOfApples = "4";
in "I have $ apples"
The output will be:
I have 4 apples
ParaSail
const Apples := 4
const Bananas := 3
Println ("I have `(Apples) apples.\n")
Println ("I have `(Apples+Bananas) fruit.\n")
The output will be:
I have 4 apples.
I have 7 fruit.
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
The output will be:
There are 5 apples and 3 bananas.
I have 5 apples and 3 bananas.
Python
Python supports string interpolation as of version 3.6, referred to as
"formatted string literals". Such a literal begins with an f
or F
before the opening quote, and uses braces for placeholders:
apples = 4
bananas = 3
print(f'I have apples and bananas')
The output will be:
I have 4 apples and 3 bananas
Ruby / Crystal
apples = 4
puts "I have # apples"
# or
puts "I have %s apples" % apples
# or
puts "I have % apples" %
The output will be:
I have 4 apples
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 th
std::fmt
module, which is interfaced with through various macros such a
an
These macros are converted into Rust source code at compile-time, whereby each argument interacts with
The formatter support
positional parameters
named parameters
argument types
defining variou
formatting traits
and capturing identifiers from the environment.
let (apples, bananas) = (4, 3);
// println! captures the identifiers when formatting: the string itself isn't interpolated by Rust.
println!("There are apples and bananas.");
The output will be:
There are 4 apples and 3 bananas.
Scala
Scala 2.10+ has implemented the following string interpolators: s, f and raw. 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("I have %d apples\n", apples)
println("I have %d apples" format apples)
//Scala 2.10+
println(s"I have $apples apples")
println(s"I have $ fruits")
println(f"I have $apples%d apples")
The output will be:I have 4 apples
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(I have apples
);
domElement.$append(I have fruits
);
Where domElement.$content(I have apples
); gets compiled to this:
domElement.html = "I have " + apples.toHtmlString() + " apples
";
Snobol
apples = 4 ; bananas = 3
Output = "I have " apples " apples."
Output = "I have " (apples + bananas) " fruit."
The output will be:
I have 4 apples.
I have 7 fruit.
Swift
In Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* 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
print("I have \(apples) apples")
The output will be:
I have 4 apples
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:
I have 4 apples.
In order to actually format - and not simply replace - the values, there is a formatting function.
set apples 4
puts ormat "I have %d apples." $apples
TypeScript
As of version 1.4, TypeScript
TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large appl ...
supports string interpolation using backticks ``
. Here is an example:
var apples: number = 4;
console.log(`I have $ apples`);
The output will be:
I have 4 apples
The console.log
function can be used as a printf
function. The above example can be rewritten, thusly:
var apples: number = 4;
console.log("I have %d apples", apples);
The output remains the same.
Visual Basic
As of Visual Basic 14, String Interpolation is supported in Visual Basic.
name = "Tom"
Console.WriteLine($"Hello, ")
will print "Hello, Tom".
See also
* Concatenation
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenat ...
* Improper input validation
* printf format string
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
* Quasi-quotation
* String literal
A string literal or anonymous string is a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally " bracketed delimiters", as in x = "foo", where "foo" is a string ...
* Substitution
Notes
{{Reflist
Programming constructs
Interpolation
In the mathematical field of numerical analysis, interpolation is a type of estimation, a method of constructing (finding) new data points based on the range of a discrete set of known data points.
In engineering and science, one often has ...
Variable (computer science)