String interpolation: Difference between revisions

Content deleted Content added
m Examples: lang="output"
Citation bot (talk | contribs)
Add: title, date. Changed bare reference to CS1/2. | Use this bot. Report bugs. | Suggested by Folkezoft | Linked from User:Folkezoft/sandbox | #UCB_webform_linked 829/978
 
(45 intermediate revisions by 25 users not shown)
Line 1:
{{short description|Replacing placeholders in a string with values}}
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 [[Form (document)#Placeholders|placeholders]], yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple [[Template processor|template processing]]<ref>"[httphttps://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf Enforcing Strict Model-View Separation in Template Engines]", T. Parr (2004), WWW2004 conference.</ref> or, in formal terms, a form of [[quasi-quotation]] (or logic [[Substitution_Substitution (logic)|substitution]] interpretation). The placeholder may be a variable name, or in some languages an arbitrary expression, in either case evaluated in the current [[Scope (computer science)|context]].
 
String interpolation is an alternative to building string via [[concatenation]], which requires repeatedrepeat quoting and unquoting;<ref>{{Cite web|url=http://perlmeme.org/howtos/using_perl/interpolation.html|title = Interpolation in Perl |date = 12 December 2024 |quote="This is much tidier than repeatedrepeat uses of the '.' concatenation operator."}}</ref> or substituting into a [[printf format string]], where the variable is far from where it is used. Compare:
<syntaxhighlight lang="pythonruby">
apples = 4
print(puts "I have $#{apples} apples.") # string interpolation
print(puts "I have " + String(apples) + " apples.") # string concatenation
print(puts "I have %sd apples.", % apples) # format string
</syntaxhighlight>
 
Two types of literal expression are usually offered: one with interpolation enabled, the other without. Non-interpolated strings may also [[escape sequence]]s, 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 (computer programming)|sigil]] (typically <code>$</code> or <code>%</code>), e.g. <code>$apples</code> or <code>%apples</code>, or with braces, e.g. <code>{apples}</code>, sometimes both, e.g. <code>${apples}</code>. In some cases additional formatting specifiers can be used (as in printf), e.g. <code>{apples:3}</code>, and in some cases the formatting specifiers themselves can be interpolated, e.g. <code>{apples:width}</code>. Expansion of the string usually occurs at [[run time (program lifecycle phase)|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]]s which make heavy use of [[String (computer science)|string]] representations of data, such as [[Groovy (programming language)|Apache Groovy]], [[Julia (programming language)|Julia]], [[Kotlin (programming language)|Kotlin]], [[Perl]], [[PHP]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]], [[Scala (programming language)|Scala]], [[Swift (programming language)|Swift]], [[Tcl]] and most [[Unix shell]]s.
 
== Algorithms ==
There are two main types of expand variable-expanding algorithms for ''variable interpolation'':<ref>[https://code.google.com/p/smallest-template-system/wiki/SimplestAlgorithm "smallest-template-system/Simplest algorithms"], an online tutorial for placeholder-template-systems.</ref>
# ''Replace and expand placeholders'': creating a new string from the original one, by find-replacefind–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 joinjoining items by concatenation. The split string can be cached tofor 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 Externalexternal Entityentity Injection]]attack|XML external entity (XXE) injection]], and [[cross-site scripting]] (XSS) attacks.<ref>{{cite web |url=http://google-caja.googlecode.com/svn/changes/mikesamuel/string-interpolation-29-Jan-2008/trunk/src/js/com/google/caja/interp/index.html#-autogen-id-1 {{Webarchive|title= Secure String Interpolation|website=google-caja.googlecode.com |archive-url=https://web.archive.org/web/20121019065315/http://google-caja.googlecode.com/svn/changes/mikesamuel/string-interpolation-29-Jan-2008/trunk/src/js/com/google/caja/interp/index.html#-autogen-id-1 |archive-date=2012-10-19 }}</ref>
 
An SQL injection example:
query = "{{code|2=sql|1=SELECT x, y, z FROM Table WHERE id='$id'}} "
If ''<code>$id</code>'' is replaced with ''"<code>'; {{code|2=sql|1=DELETE FROM Table; SELECT * FROM Table WHERE id='}}</code>"'', executing this query will wipe out all the data in <code>Table</code>.
 
== Examples ==
Line 66:
Console.WriteLine($"I have {apples} apples");
Console.WriteLine($"I have {apples + bananas} fruits");
</syntaxhighlight><ref>{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-interpolation|title = Strings - C# Programming Guide| date=15 March 2024 }}</ref>
 
The output will be:
Line 101:
=== Dart ===
{{Main|Dart (programming language)}}
<syntaxhighlight lang="ecmascriptdart">
int apples = 4, bananas = 3;
print('I have $apples apples.');
print('I have ${apples+bananas} fruitfruits.');
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">I have 4 apples.
I have 7 fruitfruits.</syntaxhighlight>
 
=== Go ===
{{Main|Go (programming language)}}
{{as of|20222025}}, Go does not have string interpolation. There have been some proposals for string interpolation, inwhich thehave nextbeen version of the language, Go 2rejected.<ref>{{cite web|url=https://github.com/golang/go/issues/34174 |title=proposal: Go 2: string interpolation #34174|website=[[GitHub]] }}</ref><ref>{{cite web|url=https://github.com/golang/go/issues/50554 |title=proposal: Go 2: string interpolation evaluating to string and list of expressions #50554|website=[[GitHub]] }}</ref><ref>{{Cite Instead,web Go|title=proposal: usesspec: [[printfadd formatsimple string]]s ininterpolation thesimilar <code>fmt.Sprintf</code>to function,Swift string· [[concatenation]],Issue or#57616 template· librariesgolang/go like|url=https://github.com/golang/go/issues/57616 |access-date=2025-05-19 |website=GitHub |language=en}}<code>text/template</coderef>.
 
=== Groovy ===
Line 120:
def quality = "superhero"
final age = 52
def sentence = "A developer is a $quality, if he is ${age <= 42 ? "'young"' : "'seasoned"'}"
println sentence
</syntaxhighlight>
Line 132:
var bananas = 3;
trace('I have $apples apples.');
trace('I have ${apples+bananas} fruitfruits.');
echo(sentence)</syntaxhighlight>
IThe haveoutput 7will fruit.</syntaxhighlight>be:<ref>{{Cite news|url=https://haxe.org/manual/lf-string-interpolation.html|title=Haxe - Manual - String interpolation|work=Haxe - The Cross-platform Toolkit|access-date=2017-09-12}}</ref>
<syntaxhighlight lang="ecmascriptoutput">
I have 4 apples.
I have 7 fruits.
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">I have 4 apples.
I have 7 fruit.</syntaxhighlight><ref>{{Cite news|url=https://haxe.org/manual/lf-string-interpolation.html|title=Haxe - Manual - String interpolation|work=Haxe - The Cross-platform Toolkit|access-date=2017-09-12}}</ref>
 
=== Java ===
{{Main article|Java (programming language)}}
Java had interpolated strings as a preview feature in Java 21 and Java 22. You could use the constant STR of [https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/StringTemplate.html java.lang.StringTemplate] directly.<syntaxhighlight lang="java" line="1">
{{as of|2022}}, Java does not have interpolated strings, and instead uses format functions, notably the <code>MessageFormat</code> class (Java version 1.1 and above) and the static method <code>String.format</code> (Java version 5 and above).
enum Stage{test,qa,prod}
record Deploy(UUID image, Stage stage){}
var deploy=new Deploy(UUID.randomUUID(), Stage.test)
STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."
var deploy=new Deploy(UUID.randomUUID(), Stage.prod)
STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."
</syntaxhighlight>
 
They were removed in Java 23 due to design issues.<ref>{{cite web | title=Significant Changes in the JDK | url=https://docs.oracle.com/en/java/javase/23/migrate/significant-changes-jdk-release.html }}</ref>
 
=== JavaScript ===
{{Main article|JavaScript}}
[[JavaScript]], as of the [[ECMAScript]] 2015 (ES6) standard, supports string interpolation using backticks <code>``</code>. This feature is called ''template literals''.<ref>{{Cite web|url=https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals|title = Template literals (Template strings) - JavaScript &#124; MDN| date=31 May 2024 }}</ref> Here is an example:
 
<syntaxhighlight lang="outputjavascript">I have 4 apples.
[[JavaScript]], as of the [[ECMAScript]] 2015 (ES6) standard, supports string interpolation using backticks <code>``</code>. This feature is called ''template literals''.<ref>{{Cite web|url=https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals|title = Template literals (Template strings) - JavaScript &#124; MDN}}</ref> Here is an example:
<syntaxhighlight lang="ecmascript">
const apples = 4;
const bananas = 3;
console.log(`I have ${apples} apples`);
console.log(`I have ${apples + bananas} fruitfruits`);
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">
I have 4 apples
I have 7 fruitfruits
</syntaxhighlight>
 
Template literals can also be used for multi-line strings:
<syntaxhighlight lang="ecmascriptjavascript">
console.log(`This is the first line of text.
This is the second line of text.`);
Line 188 ⟶ 198:
val apples = 4
val bananas = 3
val sentence = "A developer is a $quality. I have ${apples + bananas} fruitfruits"
println(sentence)
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">
A developer is a superhero. I have 7 fruitfruits
</syntaxhighlight>
 
=== Nemerle ===
Line 207 ⟶ 219:
<syntaxhighlight lang="output">apples
bananas</syntaxhighlight>
 
=== Next Generation Shell ===
{{Main|Next Generation Shell}}
The recommended syntax is <code>${expr}</code> though <code>$var</code> is also supported:
<syntaxhighlight lang="sh">quality = "superhero"
apples = 4
bananas = 3
sentence = "A developer is a $quality. I have ${apples + bananas} fruit"
echo(sentence)</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">A developer is a superhero. I have 7 fruit</syntaxhighlight>
 
=== Nim ===
Line 277 ⟶ 278:
const Bananas := 3
Println ("I have `(Apples) apples.\n")
Println ("I have `(Apples+Bananas) fruitfruits.\n")
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">
I have 4 apples.
I have 7 fruitfruits.
</syntaxhighlight>
 
=== Perl ===
Line 303 ⟶ 305:
$apples = 5;
$bananas = 3;
echo "There are $apples apples and $bananas bananas.\n";
echo "\n";
echo "I have {$apples} apples and {$bananas} bananas.";
</syntaxhighlight>The output will be:
Line 313 ⟶ 314:
{{Main|Python (programming language)}}
Python supports string interpolation as of version 3.6, referred to as
"formatted string literals" or "f-strings".<ref>{{cite web |url=https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings
|title= The Python Tutorial: 7.1.1. Formatted String Literals}}</ref><ref>{{Cite web |url=https://docs.python.org/3/reference/lexical_analysis.html#f-strings |title=The Python Language Reference: 2.4.3. Formatted string literals}}</ref><ref>{{Cite web|url=https://www.python.org/dev/peps/pep-0498/|title = PEP 498 -- Literal String Interpolation}}</ref> Such a literal begins with an <code>f</code> or <code>F</code> before the opening quote, and uses braces for placeholders:
<syntaxhighlight lang="python">
applesnum_apples = 4
bananasnum_bananas = 3
print(f'I have {applesnum_apples} apples and {bananasnum_bananas} bananas')
</syntaxhighlight>
The output will be:
Line 330 ⟶ 331:
apples = 4
puts "I have #{apples} apples"
# Format string applications for comparison:
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}
</syntaxhighlight>
Line 352:
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="shoutput">quality = "superhero"
There are 4 apples and 3 bananas.
</syntaxhighlight>
 
=== Scala ===
{{Main article|Scala (programming language)}}
 
[[Scala (programming language)|Scala]] 2.10+ hasprovides implementeda thegeneral followingfacility to allow arbitrary processing of a string interpolators:literal, and supports string interpolation using the included <code>s,</code> and <code>f</code> andstring rawinterpolators. It is also possible to write custom ones or override the standard ones.
 
The <code>f</code> 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 ====
Line 378 ⟶ 380:
 
=== Sciter (tiscript) ===
{{Main article|Sciter (HTML/CSS UI Engine)}}
 
In Sciter any function with name starting from $ is considered as interpolating function and so interpolation is customizable and context sensitive:
<syntaxhighlight lang="javascript">
Line 398:
apples = 4 ; bananas = 3
Output = "I have " apples " apples."
Output = "I have " (apples + bananas) " fruitfruits."
</syntaxhighlight>
The output will be:
<syntaxhighlight lang="output">
I have 4 apples.
I have 7 fruitfruits.
</syntaxhighlight>
 
=== Swift===
Line 427 ⟶ 429:
<syntaxhighlight lang="output">I have 4 apples.</syntaxhighlight>
 
In order to actually format - and not simply replace - the values, there is a formatting function.
 
<syntaxhighlight lang="tcl">
Line 438 ⟶ 440:
 
As of version 1.4, [[TypeScript]] supports string interpolation using backticks <code>``</code>. Here is an example:
<syntaxhighlight lang="ecmascripttypescript">
var apples: number = 4;
console.log(`I have ${apples} apples`);
Line 445 ⟶ 447:
<syntaxhighlight lang="output">I have 4 apples</syntaxhighlight>
The <code>console.log</code> function can be used as a <code>printf</code> function. The above example can be rewritten, thusly:
<syntaxhighlight lang="ecmascripttypescript">
var apples: number = 4;
console.log("I have %d apples", apples);
Line 451 ⟶ 453:
The output remains the same.
 
=== Visual Basic .NET ===
As of Visual Basic 14, Stringstring Interpolationinterpolation is supported in Visual Basic.<ref>{{Cite web|last=KathleenDollard|title=Interpolated Strings - Visual Basic|url=https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings|access-date=2021-06-20|website=docs.microsoft.com|language=en-us}}</ref>
<syntaxhighlight lang="ecmascriptvbnet">
name = "Tom"
Console.WriteLine($"Hello, {name}")
</syntaxhighlight>
 
The output will be:
will print "Hello, Tom".
{{sxhl|Hello, Tom|output}}
 
== See also ==
Line 467 ⟶ 470:
* [[Quasi-quotation]]
* [[String literal]]
* [[Substitution_Substitution (logic)|Substitution]]
 
== Notes ==