String interpolation: Difference between revisions

Content deleted Content added
Python: reflects that f strings are not the only type of string interpolation available in python, although it is the most modern approach currently.
Tag: Reverted
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
 
(13 intermediate revisions by 11 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 (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 repeat 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 repeat 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="ruby">
apples = 4
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 112:
=== 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 142:
=== 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). [https://openjdk.org/jeps/430 There is a proposal] to add string interpolation to the Java language. This proposal aims at doing safe string interpolation, making it easier to prevent injection attacks.
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:
 
[[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="javascript">
const apples = 4;
Line 306 ⟶ 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. This type of string interpolation is known as an "f string", and is the recommended modern option. Older methods of string interpolation in Python include the <code>%</code> operator and the <code>str.format()</code> method<ref>{{Cite web|url=https://ioflood.com/blog/python-string-formatting/#Advanced_Python_String_Formatting
|title=Python String Formatting|website=ioflood.com|access-date=2023-12-09}}</ref>. Here is an example of using f-strings:
<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 422 ⟶ 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 446 ⟶ 453:
The output remains the same.
 
=== Visual Basic .NET ===
As of Visual Basic 14, string interpolation 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>