Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

String interpolation

From Wikipedia, the free encyclopedia
Replacing placeholders in a string with values

Incomputer programming,string interpolation (orvariable interpolation,variable substitution, orvariable expansion) is the process of evaluating astring literal containing one or moreplaceholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simpletemplate processing[1] or, in formal terms, a form ofquasi-quotation (or logicsubstitution interpretation). The placeholder may be a variable name, or in some languages an arbitrary expression, in either case evaluated in the currentcontext.

String interpolation is an alternative to building a string viaconcatenation, which requires repeat quoting and unquoting;[2] or substituting into aprintf format string, where the variable is far from where it is used. Consider this example inRuby:

apples=4puts"I have#{apples} apples."# string interpolationputs"I have "+String(apples)+" apples."# string concatenationputs"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 alsoescape sequences, in which case they are termed araw 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 namedsigil (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 atrun 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 manyprogramming languages which make heavy use ofstring representations of data, such asApache Groovy,Julia,Kotlin,Perl,PHP,Python,Ruby,Scala,Swift,Tcl and mostUnix shells.

Algorithms

[edit]

There are two main types of variable-expanding algorithms forvariable interpolation:[3]

  1. Replace and expand placeholders: creating a new string from the original one, by find–replace operations. Find variable reference (placeholder), replace it with its variable value. This algorithm offers no cache strategy.
  2. 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

[edit]

String interpolation, like string concatenation, may lead to security problems. If user input data is improperly escaped or filtered, the system will be exposed toSQL injection,script injection,XML external entity (XXE) injection, andcross-site scripting (XSS) attacks.[4]

An SQL injection example:

query = "SELECTx,y,zFROMTableWHEREid='$id' "

If$id is replaced with"';DELETEFROMTable;SELECT*FROMTableWHEREid='", executing this query will wipe out all the data inTable.

Examples

[edit]

ABAP

[edit]
Main article:ABAP
DATA(apples)=4.WRITE|I have{apples} apples|.

The output will be:

I have 4 apples

Bash

[edit]
Main article:Bash (Unix shell)
apples=4echo"I have$apples apples"# orecho"I have${apples} apples"

The output will be:

I have 4 apples

Boo

[edit]
Main article:Boo (programming language)
apples=4print("I have $(apples) apples")# orprint("I have {0} apples"%apples)

The output will be:

I have 4 apples

C

[edit]
Main article:C (programming language)

C does not have interpolated strings, but they can be approximated usingsprintf() from<stdio.h>.

#include<stdio.h>#define BUFFER_SIZE 100intmain(){charsentence[BUFFER_SIZE];intage=20;floatheight=5.9;charname[]="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.}

C++

[edit]
Main article:C++

While interpolated strings do not exist in C++, they can be approximated usingstd::format andstd::print functions.

importstd;usingstd::string;intmain(){intapples=4;intbananas=3;std::println("I have {} apples",apples);// format specifiersstd::println("I have {0} fruits, of which there are {1} apples and {2} bananas",apples+bananas,apples,bananas);// specify position explicitly// using std::format():stringname="John Doe";intage=20;stringgreeting=std::format("Hello, {}! You are {} years old.",name,age);}

Interpolated strings have been proposed for inclusion into C++, based onthe {fmt} library.[5]

C#

[edit]
Main article:C Sharp (programming language)
publicclassExample{staticvoidMain(string[]args){intapples=4;intbananas=3;Console.WriteLine($"I have {apples} apples");Console.WriteLine($"I have {apples + bananas} fruits");}}

[6]

The output will be:

I have 4 applesI have 7 fruits

This can also be done usingString.Format().

usingSystem;publicclassExample{staticvoidMain(string[]args){intapples=4;intbananas=3;Console.WriteLine(String.Format("I have {0} apples and {1} bananas.",apples,bananas));}}

ColdFusion Markup Language

[edit]
Main article:ColdFusion Markup Language

ColdFusion Markup Language (CFML) script syntax:

apples=4;writeOutput("I have#apples# apples");

Tag syntax:

<cfsetapples=4><cfoutput>I have#apples# apples</cfoutput>

The output will be:

I have 4 apples

CoffeeScript

[edit]
Main article:CoffeeScript
apples=4console.log"I have#{apples} apples"

The output will be:

I have 4 apples

Dart

[edit]
Main article:Dart (programming language)
intapples=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.

Go

[edit]
Main article:Go (programming language)

While there have been some proposals for string interpolation (which have been rejected),[7][8][9] As of 2025[update] Go does not have interpolated strings.

However, they can be approximated usingfmt.Sprintf().

import"fmt"funcmain(){// message is of type stringmessage:=fmt.Sprintf("My name is %s and I am %d years old.","John Doe",20)fmt.Println(message)}

Groovy

[edit]
Main article:Groovy (programming language)

In groovy, interpolated strings are known as GStrings:[10]

defquality="superhero"finalage=52defsentence="A developer is a $quality if he is ${age <= 42 ? 'young' : 'seasoned'}"printlnsentence

The output will be:

A developer is a superhero if he is seasoned

Haxe

[edit]
Main article:Haxe
varapples=4;varbananas=3;trace('I have$apples apples.');trace('I have${apples+bananas} fruits.');

The output will be:[11]

I have 4 apples.I have 7 fruits.

Java

[edit]
Main article:Java (programming language)

Java had interpolated strings as a preview feature in Java 21 and Java 22. One could use the constant STR ofjava.lang.StringTemplate directly.

enumStage{TEST,QA,PRODUCTION}recordDeploy(UUIDimage,Stagestage){}publicclassExample{publicstaticvoidmain(String[]args){Deploydeploy=newDeploy(UUID.randomUUID(),Stage.TEST)STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."Deploydeploy=newDeploy(UUID.randomUUID(),Stage.PRODUCTION)STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."}}

They were removed in Java 23 due to design issues.[12]

Otherwise, interpolated strings can be approximated using theString.format() method.

publicclassExample{publicstaticvoidmain(String[]args){intapples=3;intbananas=4;Stringsentence=String.format("I have %d fruits, of which %d are apples and %d are bananas.",apples+bananas,apples,bananas);System.out.println(sentence);Stringname="John Doe";intage=20;System.out.printf("My name is %s, and I am %d years old.",name,age);}}

JavaScript/TypeScript

[edit]
Main articles:JavaScript andTypeScript

JavaScript andTypeScript, as of theECMAScript 2015 (ES6) standard, support string interpolation using backticks``. This feature is calledtemplate literals.[13] Here is an example:

constapples:number=4;constbananas:number=3;console.log(`I have${apples} apples`);console.log(`I have${apples+bananas} fruits`);

The output will be:

I have 4 applesI 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.

Julia

[edit]
Main article:Julia (programming language)
apples=4bananas=3print("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

[edit]
Main article:Kotlin (programming language)
funmain(){valquality:String="superhero"valapples:Int=4valbananas:Int=3valsentence: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

Nemerle

[edit]
Main article:Nemerle
defapples=4;defbananas=3;Console.WriteLine($"I have $apples apples.");Console.WriteLine($"I have $(apples + bananas) fruit.");

It also supports advanced formatting features, such as:

deffruit=["apple","banana"];Console.WriteLine($<#I have ..$(fruit; "\n"; f => f + "s")#>);

The output will be:

applesbananas

Nim

[edit]
Main article:Nim (programming language)

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.

importstrutils,strformatvarapples=4varbananas=3echo"I have$1 apples".format(apples)echofmt"I have {apples} apples"echofmt"I have {apples + bananas} fruits"# Multi-lineechofmt"""Ihave{apples}apples"""# Debug the formattingechofmt"I have {apples=} apples"# Custom openChar and closeChar charactersechofmt("I have (apples) {apples}",'(',')')# Backslash inside the formatted string literalechofmt"""{ "yep\nope" }"""

The output will be:

I have 4 applesI have 4 applesI have 7 fruitsI have4 applesI have apples=4 applesI have 4 {apples}yepope

Nix

[edit]
Main article:Nix package manager
letnumberOfApples="4";in"I have${numberOfApples} apples"

The output will be:

I have 4 apples

ParaSail

[edit]
Main article:ParaSail (programming language)
constApples:=4constBananas:=3Println("I have `(Apples) apples.\n")Println("I have `(Apples+Bananas) fruits.\n")

The output will be:

I have 4 apples.I have 7 fruits.

Perl

[edit]
Main article:Perl
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.

PHP

[edit]
Main article:PHP
<?php$apples=5;$bananas=3;echo"There are$apples apples and$bananas bananas.\n";echo"I have{$apples} apples and{$bananas} bananas.";

The output will be:

There are 5 apples and 3 bananas.I have 5 apples and 3 bananas.

Python

[edit]
Main article:Python (programming language)

Python supports string interpolation as of version 3.6, referred to as "formatted string literals" or "f-strings".[14][15][16] Such a literal begins with anf orF before the opening quote, and uses braces for placeholders:

num_apples:int=4num_bananas:int=3print(f'I have{num_apples} apples and{num_bananas} bananas')

The output will be:

I have 4 apples and 3 bananas

Ruby/Crystal

[edit]
Main articles:Ruby (programming language) andCrystal (programming language)
apples=4puts"I have#{apples} apples"# Format string applications for comparison:puts"I have %s apples"%applesputs"I have %{a} apples"%{a:apples}

The output will be:

I have 4 apples

Rust

[edit]
Main article:Rust (programming language)

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.[17]

Rust provides formatting via thestd::fmt module, which is interfaced with through various macros such asformat!,write!, andprint!. These macros are converted into Rust source code at compile-time, whereby each argument interacts with aformatter. The formatter supportspositional parameters,named parameters,argument types, defining variousformatting traits, and capturing identifiers from the environment.

fnmain(){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!():letsentence:String=format!("There are {0} apples and {1} bananas.",apples,bananas);println!(sentence);}

The output will be:

There are 4 apples and 3 bananas.

Scala

[edit]
Main article:Scala (programming language)

Scala 2.10+ provides a general facility to allow arbitrary processing of a string literal, and supports string interpolation using the includeds andf string interpolators. It is also possible to write custom ones or override the standard ones.

Thef 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

[edit]

Scala 2.10+'s string interpolation allows embedding variable references directly in processed string literals. Here is an example:

valapples=4valbananas=3//before Scala 2.10printf("I have %d apples\n",apples)println("I have %d apples"formatapples)//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

Sciter (tiscript)

[edit]

In Sciter any function with name starting from $ is considered as interpolating function and so interpolation is customizable and context sensitive:

varapples=4varbananas=3vardomElement=...;domElement.$content(<p>Ihave{apples}apples</p>);domElement.$append(<p>Ihave{apples+bananas}fruits</p>);

Where

domElement.$content(<p>Ihave{apples}apples</p>);

gets compiled to this:

domElement.html="<p>I have "+apples.toHtmlString()+" apples</p>";

Snobol

[edit]
Main article:SNOBOL
apples=4;bananas=3Output="I have "apples" apples."Output="I have "(apples+bananas)" fruits."

The output will be:

I have 4 apples.I have 7 fruits.

Swift

[edit]
Main article:Swift (programming language)

InSwift, a new String value can be created from a mix of constants, variables, literals, and expressions by including their values inside a string literal.[18] Each item inserted into the string literal is wrapped in a pair of parentheses, prefixed by a backslash.

letapples=4print("I have\(apples) apples")

The output will be:

I have 4 apples

Tcl

[edit]
Main article:Tcl

The Tool Command Language has always supported string interpolation in all quote-delimited strings.

setapples4puts"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.

setapples4puts[format"I have %d apples."$apples]

TypeScript

[edit]
Main article:TypeScript

As of version 1.4,TypeScript supports string interpolation using backticks``. Here is an example:

varapples:number=4;console.log(`I have${apples} apples`);

The output will be:

I have 4 apples

Theconsole.log function can be used as aprintf function. The above example can be rewritten, thusly:

varapples:number=4;console.log("I have %d apples",apples);

The output remains the same.

Visual Basic .NET

[edit]

As of Visual Basic 14, string interpolation is supported in Visual Basic.[19]

name="Tom"Console.WriteLine($"Hello, {name}")

The output will be:

Hello, Tom

See also

[edit]

Notes

[edit]
  1. ^"Enforcing Strict Model-View Separation in Template Engines", T. Parr (2004), WWW2004 conference.
  2. ^"Interpolation in Perl". 12 December 2024.This is much tidier than repeat uses of the '.' concatenation operator.
  3. ^"smallest-template-system/Simplest algorithms", an online tutorial for placeholder-template-systems.
  4. ^"Secure String Interpolation".google-caja.googlecode.com. Archived fromthe original on 2012-10-19.
  5. ^Bengt Gustafsson, Victor Zverovich (14 October 2024)."String interpolation - p3412r0"(PDF).open-std.org. WG 21.
  6. ^"Strings - C# Programming Guide". 15 March 2024.
  7. ^"proposal: Go 2: string interpolation #34174".GitHub.
  8. ^"proposal: Go 2: string interpolation evaluating to string and list of expressions #50554".GitHub.
  9. ^"proposal: spec: add simple string interpolation similar to Swift · Issue #57616 · golang/go".GitHub. Retrieved2025-05-19.
  10. ^"The Apache Groovy programming language - Syntax".groovy-lang.org. Retrieved2021-06-20.
  11. ^"Haxe - Manual - String interpolation".Haxe - The Cross-platform Toolkit. Retrieved2017-09-12.
  12. ^"Significant Changes in the JDK".
  13. ^"Template literals (Template strings) - JavaScript | MDN". 31 May 2024.
  14. ^"The Python Tutorial: 7.1.1. Formatted String Literals".
  15. ^"The Python Language Reference: 2.4.3. Formatted string literals".
  16. ^"PEP 498 -- Literal String Interpolation".
  17. ^"Announcing Rust 1.58.0: Captured identifiers in format strings". 2022-01-13.
  18. ^"Strings and Characters — The Swift Programming Language (Swift 5.5)".docs.swift.org. Retrieved2021-06-20.
  19. ^KathleenDollard."Interpolated Strings - Visual Basic".docs.microsoft.com. Retrieved2021-06-20.
Retrieved from "https://en.wikipedia.org/w/index.php?title=String_interpolation&oldid=1322876440"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp