String interpolation
≈ 11 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
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. 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. 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} apples." # string interpolation puts "I have " + String(apples) + " 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 (but escaped) string, interpolated (and escaped) string.…
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. 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. 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} apples." # string interpolation puts "I have " + String(apples) + " 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 (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 (typically $ or % ), e.g. $apples or %apples , or with braces, e.g. {apples} , sometimes both, e.g. ${apples} . In some cases, additional formatting specifiers can be used (as in printf), e.g. {apples:3} , and in some cases the formatting specifiers themselves can be interpolated, e.g. {apples:width} . 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. query = " " If $id is replaced with " '; ", executing this query will wipe out all the data in Table . DATA(apples) = 4. WRITE |I have { apples } apples|. The output will be: I have 4 apples apples=4 echo "I have $apples apples" or echo "I have ${apples} apples" The output will be: I have 4 apples apples = 4 print("I have $(apples) apples") or print("I have {0} apples" % apples) The output will be: I have 4 apples include define BUFFER_SIZE 100 int main() { char sentence[BUFFER_SIZE]; int age = 20; float height = 5.9; char name[] = "Alice"; sprintf(sentence, "My name is %s and I am %d years old, and I am %.1f feet tall.", name, age, height); printf(sentence); // prints: // My name is Alice, and I am 20 years old, and I am 5.9 feet tall. } import std; using std::string; int main() { int apples = 4; int bananas = 3; std::println("I have {} apples", apples); // format specifiers std::println("I have {0} fruits, of which there are {1} apples and {2} bananas", apples + bananas, apples, bananas); // specify position explicitly // using std::format(): string name = "John Doe"; int age = 20; string greeting = std::format("Hello, {}! You are {} years old.", name, age); } 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 {fmt}. 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(int x) { // ... } string represent(string_view prefix, int bits) { return f"{prefix}-{__LINE__}: got {calculate(bits)} for {bits:#06x}"; } void display(string_view prefix, int bits) { std::print(f"{prefix}-{__LINE__}: got {calculate(bits)} for {bits:#06x}"); } int apples = 4; int bananas = 3; Console.WriteLine($"I have {apples} apples"); Console.WriteLine($"I have {apples + bananas} fruits"); The output will be: I have 4 apples I have 7 fruits This can also be done using String.Format() . int apples = 4; int bananas = 3; Console.WriteLine(String.Format("I have {0} apples and {1} bananas.", apples, bananas)); apples = 4; writeOutput("I have #apples# apples"); Tag syntax: I have #apples# apples The output will be: apples = 4 console.log "I have #{apples} apples" The output will be: I have 4 apples int apples = 4, bananas = 3; print('I have $apples apples.'); print('I have ${apples+bananas} fruits.'); The output will be: I have 4 apples. I have 7 fruits. import "fmt" func main() { // message is of type string message := fmt.Sprintf("My name is %s and I am %d years old.", "John Doe", 20) fmt.Println(message) } def quality = "superhero" final age = 52 def sentence = "A developer is a $quality if he is ${age The output will be: A developer is a superhero if he is seasoned var apples = 4; var bananas = 3; trace('I have $apples apples.'); trace('I have ${apples+bananas} fruits.'); The output will be: I have 4 apples. I have 7 fruits. package org.wikipedia.examples; enum Stage { TEST, QA, PRODUCTION } record Deploy(UUID image, Stage stage) {} public class Example { public static void main(String[] args) { Deploy deploy = new Deploy(UUID.randomUUID(), Stage.TEST) STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..." Deploy deploy = new Deploy(UUID.randomUUID(), Stage.PRODUCTION) STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..." } } 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 { public static void main(String[] args) { int apples = 3; int bananas = 4; String sentence = String.format("I have %d fruits, of which %d are apples and %d are bananas.", apples + bananas, apples, bananas); System.out.println(sentence); String name = "John Doe"; int age = 20; System.out.printf("My name is %s, and I am %d years old.", name, age); } } const apples: number = 4; const bananas: number = 3; console.log(`I have ${apples} apples`); console.log(`I have ${apples + bananas} fruits`); The output will be: I have 4 apples I have 7 fruits 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. 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. fun main() { val quality: String = "superhero" val apples: Int = 4 val bananas: Int = 3 val sentence: String = "A developer is a $quality. I have ${apples + bananas} fruits" println(sentence) } The output will be: A developer is a superhero. I have 7 fruits 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($ f + "s")#>); The output will be: apples bananas import strutils, strformat var apples = 4 var bananas = 3 echo "I have $1 apples".format(apples) echo fmt"I have {apples} apples" echo fmt"I have {apples + bananas} fruits" Multi-line echo fmt""" I have {apples} apples""" Debug the formatting echo fmt"I have {apples=} apples" Custom openChar and closeChar characters echo fmt("I have (apples) {apples}", '(', ')') Backslash inside the formatted string literal echo fmt"""{ "yep\nope" }""" 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 {apples} yep ope let numberOfApples = "4"; in "I have ${numberOfApples} apples" The output will be: I have 4 apples const Apples := 4 const Bananas := 3 Println ("I have `(Apples) apples.\n") Println ("I have `(Apples+Bananas) fruits.\n") The output will be: I have 4 apples. I have 7 fruits. my $apples = 4; my $bananas = 3; print "I have $apples apples.\n"; print "I have @{[$apples+$bananas]} fruit.\n"; # Uses the Perl array (@) interpolation. The output will be: I have 4 apples. I have 7 fruit. The output will be: There are 5 apples and 3 bananas. I have 5 apples and 3 bananas. apples: int = 4 bananas: int = 3 print(f"I have {apples} apples and {bananas} bananas") The output will be: I have 4 apples and 3 bananas apples = 4 puts "I have #{apples} apples" Format string applications for comparison: puts "I have %s apples" % apples puts "I have %{a} apples" % {a: apples} The output will be: I have 4 apples fn main() { let (apples, bananas): (i32, i32) = (4, 3); // println! captures the identifiers when formatting: the string itself isn't interpolated by Rust. println!("There are {apples} apples and {bananas} bananas."); // alternatively, with format!(): let sentence: String = format!("There are {0} apples and {1} bananas.", apples, bananas); println!(sentence); } The output will be: There are 4 apples and 3 bananas. 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 ${apples + bananas} fruits") println(f"I have $apples%d apples") The output will be: I have 4 apples var apples = 4 var bananas = 3 var domElement = ...; domElement.$content( I have {apples} apples ); domElement.$append( I have {apples + bananas} fruits ); Where domElement.$content( I have {apples} apples ); gets compiled to this: domElement.html = " I have " + apples.toHtmlString() + " apples "; === 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 print("I have \(apples) apples") The output will be: I have 4 apples 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 [format "I have %d apples." $apples] name = "Tom" Console.WriteLine($"Hello, {name}") The output will be:
Text derived from https://en.wikipedia.org/w/index.php?oldid=1378825025 under CC BY-SA 4.0; modifications have been made.