String interpolation (included): Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
Alextretyak (talk | contribs) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(34 intermediate revisions by 22 users not shown) | |||
Line 25:
=={{header|11l}}==
<
print(‘Mary had a ’extra‘ lamb.’)
print(‘Mary had a #. lamb.’.format(extra))
print(f:
{{out}}
Line 39:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program insertString64.s */
Line 295:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<
CHAR ARRAY extra="little"
PrintF("Mary had a %S lamb.%E",extra)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_interpolation_(included).png Screenshot from Atari 8-bit computer]
Line 310:
=={{header|Ada}}==
<
use Ada.Strings, Ada.Text_IO;
procedure String_Replace is
Line 320:
Put_Line (Fixed.Replace_Slice (
Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;</
Alternatively
<
=={{header|Aikido}}==
<
printf ("Mary had a %s lamb\n", little)
// alternatively
println ("Mary had a " + little + " lamb")</
=={{header|ALGOL 68}}==
Line 341:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - requires formatted transput}}
'''string'''s are simply '''flex''' arrays of '''char'''. '''format'''s on the other hand take on some of the properties of '''proc'''edures including the scoping rules.
<
# as a STRING #
STRING extra = "little";
Line 352:
# or: use simply use STRING concatenation #
print(("Mary had a "+extra+" lamb.", new line))
)</
{{out}}
<pre>
Line 359:
Mary had a little lamb.
</pre>
Algol 68 allows a string to be used as a file, the following (based on the above) uses this to construct the string which can then be further processed. In this sample, variable strings and formats are used though in general it would be hard to construct the extraf format at run-time as Algol 68 has no facilities to construct formats on the fly.
<syntaxhighlight lang="algol68">
BEGIN
FILE str file;
STRING mhl;
associate( str file, mhl );
STRING extra := "little";
TO 2 DO
putf( str file, ( $"Mary had a "g" lamb."$, extra ) );
print( ( "1 result is: {{", mhl, "}}", newline ) );
mhl := "";
"supposedlly-" +=: extra
OD;
FORMAT extraf := $"little"$;
TO 2 DO
putf( str file, ( $"Mary had a "f(extraf)" lamb."$ ) );
print( ( "2 result is: {{", mhl, "}}", newline ) );
mhl := "";
extraf := $"medium-sized"$
OD
END
</syntaxhighlight>
{{out}}
<pre>
1 result is: {{Mary had a little lamb.}}
1 result is: {{Mary had a supposedlly-little lamb.}}
2 result is: {{Mary had a little lamb.}}
2 result is: {{Mary had a medium-sized lamb.}}
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program insertString.s */
Line 615 ⟶ 650:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 625 ⟶ 660:
insert abcdef
</pre>
=={{header|APL}}==
<syntaxhighlight lang="apl">
s ← 'Mary had a ∆ lamb' ⋄ s[s⍳'∆'] ← ⊂'little' ⋄ s ← ∊s
s
Mary had a little lamb
⍝⍝⍝ Or, for a more general version which interpolates multiple positional arguments and can
⍝⍝⍝ handle both string and numeric types...
∇r ← s sInterp sv
⍝⍝ Interpolate items in sv into s (string field substitution)
⍝ s: string - format string, '∆' used for interpolation points
⍝ sv: vector - vector of items to interpolate into s
⍝ r: interpolated string
s[('∆'=s)/⍳⍴s] ← ⊃¨(⍕¨sv)
r ← ∊s
∇
'Mary had a ∆ lamb, its fleece was ∆ as ∆.' sInterp 'little' 'black' 'night'
Mary had a little lamb, its fleece was black as night.
'Mary had a ∆ lamb, its fleece was ∆ as ∆.' sInterp 'little' 'large' 42
Mary had a little lamb, its fleece was large as 42.
</syntaxhighlight>
=={{header|Arturo}}==
<
print ~"Mary had a |sizeOfLamb| lamb."</
{{out}}
<pre>Mary had a little lamb.</pre>
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">string s1 = "big";
write("Mary had a " + s1 + " lamb");
s1 = "little";
write("Mary also had a ", s1, "lamb");</syntaxhighlight>
=={{header|AutoHotkey}}==
<
LIT = little
string = Mary had a %LIT% lamb.
Line 644 ⟶ 708:
string := "Mary had a" LIT " lamb."
MsgBox %string%</
Documentation: [http://www.autohotkey.com/docs/Variables.htm#Variables Variables] (see '''Storing values in variables''' and '''Retrieving the contents of variables''')
Line 650 ⟶ 714:
=={{header|AWK}}==
String interpolation is usually done with functions sub() and gsub(). gawk has also gensub().
<
BEGIN {
str="Mary had a # lamb."
gsub(/#/, "little", str)
print str
}</
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="qbasic">10 x$ = "big"
20 print "Mary had a "; x$; " lamb"</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">x$ = "big"
print "Mary had a "; x$; " lamb"
x$ = "little"
print "Mary also had a "; ljust(x$, length(x$)); " lamb"</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 x$ = "big"
20 print "Mary had a "; x$; " lamb"</syntaxhighlight>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">10 X$ = "big"
20 PRINT "Mary had a "; X$; " lamb"
30 X$ = "little"
40 PRINT USING "Mary also had a & lamb"; X$
50 END</syntaxhighlight>
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 LET X$ = "BIG"
20 PRINT "MARY HAD A "; X$; " LAMB"
30 END</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">x$ = "big"
PRINT "Mary had a "; x$; " lamb"
x$ = "little"
PRINT USING "Mary also had a & lamb"; x$
' this code above doesn't modify the first string subsustituting a piece of it with another string
'surely it gives the right output on the screen</syntaxhighlight>
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 LET X$ = "BIG"
20 PRINT "Mary had a "; x$; " lamb"</syntaxhighlight>
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET x$ = "big"
PRINT "Mary had a "; x$; " lamb"
LET x$ = "little"
PRINT USING "Mary had another $##### lamb": x$
LET outstring$ = USING$("$#####", x$)
PRINT "Mary also had a "; outstring$; " lamb"
END</syntaxhighlight>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "String append"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
X$ = "big"
PRINT "Mary had a "; X$; " lamb"
END FUNCTION
END PROGRAN</syntaxhighlight>
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">x$ = "big"
print "Mary had a ", x$, " lamb"</syntaxhighlight>
=={{header|Batch File}}==
<
setlocal enabledelayedexpansion
call :interpolate %1 %2 res
Line 668 ⟶ 808:
set str=%~2
set %3=!pat:X=%str%!
goto :eof</
''Demo''
<
Mary had a little lamb</
=={{header|BQN}}==
<code>_interpolate</code> is a generalized string interpolation modifier that returns a function based on the replacement character given. The function will take a string on the right and replace the given symbol with the elements of the array given on its left.
Here, the symbol for Nothing(`·`) is used as a replacement character.
<syntaxhighlight lang="bqn">Str ← (3⌊•Type)◶⟨2=•Type∘⊑,0,1,0⟩
_interpolate ← {∾(•Fmt⍟(¬Str)¨𝕨)⌾((𝕗=𝕩)⊸/)𝕩}
'a'‿"def"‿45‿⟨1,2,3⟩‿0.34241 '·'_interpolate "Hi · am · and · or · float ·"</syntaxhighlight>
=={{header|Bracmat}}==
Use pattern matching to find the part of the string up to and the part of the string following the magic X. Concatenate these parts with the string "little" in the middle.
<
=={{header|C}}==
Include the <code><stdio.h></code> header to use the functions of the [[wp:Printf|printf]] family:
<
int main() {
Line 687 ⟶ 838:
printf("Mary had a %s lamb.\n", extra);
return 0;
}</
=={{header|C sharp|C#}}==
This is called [http://msdn.microsoft.com/en-us/library/txafckwd.aspx "composite formatting"] in MSDN.
<
{
static void Main()
Line 700 ⟶ 851:
System.Console.WriteLine(formatted);
}
}</
=={{header|C++}}==
<
#include <iostream>
Line 713 ⟶ 864:
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}</
{{works with|C++11}}
<
#include <string>
Line 758 ⟶ 909:
return out;
}</
=={{header|Clojure}}==
<
(println (format "Mary had a %s lamb." little)))</
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<
PROGRAM-ID. interpolation-included.
Line 777 ⟶ 928:
GOBACK
.</
=={{header|Coco}}==
Line 783 ⟶ 934:
As CoffeeScript, but [https://github.com/satyr/coco/wiki/additions#wiki-variable-interpolation-x the braces are optional if the expression to be interpolated is just a variable]:
<
console.log "Mary had a #size lamb."</
=={{header|CoffeeScript}}==
<
size = 'little'
console.log "Mary had a #{size} lamb." # Mary had a little lamb.
Line 797 ⟶ 948:
Multi-line strings and arbtrary expressions work: #{ 5 * 4 }
"""
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(format t "Mary had a ~A lamb.~%" extra))</
More documentation on the [http://www.cs.cmu.edu/Groups/AI/html/hyperspec/HyperSpec/Body/fun_format.html FORMAT] function.
=={{header|D}}==
<
import std.stdio, std.string;
"Mary had a %s lamb.".format("little").writeln;
"Mary had a %2$s %1$s lamb.".format("little", "white").writeln;
}</
{{out}}
<pre>Mary had a little lamb.
Line 818 ⟶ 969:
=={{header|Delphi}}==
<
uses
Line 853 ⟶ 1,004:
writeln(Output);
end.</
{{out}}
<pre>Mary had a little lamb.
Line 861 ⟶ 1,012:
=={{header|DWScript}}==
<
{{out}}
<pre>Mary had a little lamb.</pre>
Line 869 ⟶ 1,020:
Dyalect has a built-in [https://github.com/vorov2/dyalect/wiki/String#interpolation string interpolation] feature.
<
print("Mary had a \(lamb_size) lamb.")</
=={{header|E}}==
<
`Mary had a $adjective lamb`</
The <code>`...`</code> syntax in general may be used as a sort of syntax extension; string interpolation is just the default case. [http://www.erights.org/elang/grammar/quasi-overview.html More information on E quasi-literals.] (Note that this documentation may be somewhat out of date.)
Line 881 ⟶ 1,032:
The above code is equivalent to (expands into):
<
simple__quasiParser.valueMaker("Mary had a ${0} lamb").substitute([adjective])</
If an identifier precedes the opening <code>`</code>, then it replaces <code>simple</code>; the quasiParser may be an arbitrary user-defined object. In this way, E provides lightweight syntax for embedding other languages: XML, JSON, GUI layouts, regular expressions, etc.
Line 888 ⟶ 1,039:
=={{header|EchoLisp}}==
'''format''' and '''printf''' use replacement directives to perform interpolation. See [http://www.echolalie.org/echolisp/help.html#format format specification] in EchoLisp documentatiuon.
<
;; format uses %a or ~a as replacement directive
(format "Mary had a ~a lamb" "little")
Line 894 ⟶ 1,045:
(format "Mary had a %a lamb" "little")
→ "Mary had a little lamb"
</syntaxhighlight>
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
IMPORT STD;
STD.Str.FindReplace('Mary had a X Lamb', 'X','little');
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 910 ⟶ 1,061:
var s := "little";
console.printLineFormatted("Mary had a {0} lamb.",s).readChar()
}</
=={{header|Elixir}}==
Elixir borrows Ruby's #{...} interpolation syntax.
<
x = "little"
IO.puts "Mary had a #{x} lamb"
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let ((little "little"))
(format "Mary had a %s lamb." little)
;; message takes a format string as argument
(message "Mary had a %s lamb." little))</syntaxhighlight>
=={{header|Erlang}}==
Line 929 ⟶ 1,086:
=={{header|Euphoria}}==
<
sequence s
s = sprintf("Mary had a %s lamb.",{lambType})
puts(1,s)</
See
[http://openeuphoria.org/docs/std_text.html#_3233_sprintf sprintf],
Line 939 ⟶ 1,096:
=={{header|F_Sharp|F#}}==
[http://msdn.microsoft.com/en-us/library/ee370560(VS.100).aspx Documentation]
<
printfn "Mary had a %s lamb." lambType</
=={{header|Factor}}==
<
SYMBOL: little
Line 949 ⟶ 1,106:
"little" little set
little get "Mary had a %s lamb" sprintf</
I tried to be as specific as possible here. The challenge says to use a ''variable'' so that is what I used. It could have been done more cleanly using a CONSTANT.
<
CONSTANT: little "little"
little "Mary had a %s lamb" sprintf</
=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic''
<
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 970 ⟶ 1,127:
// line 1: use of the = operator
// line 2: use of the @ and $ operator
</syntaxhighlight>
{{out}}
<pre>
Line 981 ⟶ 1,138:
Interpolating a variable value into a string is done by using a $ prefix on the variable name within a string. For example:
<
fansh> x := "little"
little
fansh> echo ("Mary had a $x lamb")
Mary had a little lamb
</syntaxhighlight>
Documentation at: [http://fantom.org/doc/docLang/Literals.html#interpolation Fantom website]
Line 992 ⟶ 1,149:
=={{header|Forth}}==
<
variable #src
variable 'out
Line 1,018 ⟶ 1,175:
here 'out ! ," BIG" here 'out @ - #out !
format
</syntaxhighlight>
{{out}}
<pre>
Line 1,027 ⟶ 1,184:
=={{header|Fortran}}==
<
write (*,*) trim(inter("Mary had a X lamb.","X","little"))
Line 1,045 ⟶ 1,202:
end function inter
end program interpolate</
=={{header|FreeBASIC}}==
Line 1,052 ⟶ 1,209:
It is also possible to use C library functions such as printf or sprintf, which allow more conventional string interpolation,
as easily as if they were part of FB itself:
<
#Include "crt/stdio.bi" '' header needed for printf
Line 1,060 ⟶ 1,217:
x = "little"
printf("Mary also had a %s lamb", x)
Sleep</
{{out}}
Line 1,069 ⟶ 1,226:
=={{header|Frink}}==
<
println["Mary had a $x lamb."]</
=={{header|FunL}}==
<
println( "Mary had a $X lamb." )</
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
CFStringRef string, extra
extra = @"little"
string = fn StringWithFormat( @"Mary had a %@ lamb", extra )
print string
HandleEvents
</syntaxhighlight>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=29bc3d7010d216a49382a47cdeeec15f Click this link to run this code]'''
<
Print Subst("Mary had a &1 lamb", "little")
End</
Output:
<pre>
Line 1,091 ⟶ 1,259:
This kind of string interpolation is indeed a strong feature in Gastona. We add one more
indirection in the sample just to ilustrate it.
<
<how> //little
Line 1,097 ⟶ 1,265:
<main> //Mary @<what>
</syntaxhighlight>
{{out|Output}}
<pre>
Line 1,105 ⟶ 1,273:
=={{header|Go}}==
Doc: [http://golang.org/pkg/fmt/ http://golang.org/pkg/fmt/]
<syntaxhighlight lang="go">
package main
Line 1,118 ⟶ 1,286:
fmt.Println(out)
}
</syntaxhighlight>
=={{header|Groovy}}==
<
assert 'Mary had a little lamb.' == "Mary had a ${adj} lamb."</
=={{header|Haskell}}==
Line 1,128 ⟶ 1,296:
No such facilities are defined in Haskell 98, but the <code>base</code> package distributed with GHC provides a <code>[http://hackage.haskell.org/packages/archive/base/latest/doc/html/Text-Printf.html#v:printf printf]</code> function.
<
main = printf "Mary had a %s lamb\n" "little"</
=={{header|Haxe}}==
{{trans|C#}}
<
static function main() {
var extra = 'little';
Line 1,140 ⟶ 1,308:
Sys.println(formatted);
}
}</
{{out}}
Line 1,149 ⟶ 1,317:
=={{header|HicEst}}==
[http://www.HicEst.com/EDIT Further documentation on HicEst string interpolation function EDIT()]
<
output_string = original
EDIT(Text=output_string, Right='X', RePLaceby=little)</
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon are descended from a line of languages with a wealth of string manipulation capabilities. [http://www.cs.arizona.edu/icon/ftp/doc/lb1up.pdf See The Icon Programming Language, 3rd Edition; Griswold and Griswold; Chapter 3 String Scanning]
<
s3 := "little"
s1 := "Mary had a humongous lamb."
s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0) # replaces the first instance of s2 with s3
while s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0) # replaces all instances of s2 with s3, equivalent to replace</
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/strings.icn Note the strings library includes convenient procedures for string replacement] such as replace(s1,s2,s3) which replaces all occurrences of s2 in s1 with s3 and replacem(s1,s2,s3,...) which replaces multiple pairs.
Line 1,166 ⟶ 1,334:
=={{header|J}}==
The <code>strings</code> and <code>printf</code> scripts are part of the base library.
<
'Mary had a %s lamb.' sprintf <'little'
Mary had a little lamb.
Line 1,174 ⟶ 1,342:
Mary had a little lamb.
'Mary had a %s lamb.' rplc '%s';'little'
Mary had a little lamb.</
Documentation:
Line 1,180 ⟶ 1,348:
The comments in these library files give brief descriptions of their contents, and you can browse them using open:
<syntaxhighlight lang
Alternatively, both [http://www.jsoftware.com/docs/help602/user/script_strings.htm strings] and [http://www.jsoftware.com/help/jforc/input_and_output.htm#_Toc191734427 printf] have various web pages describing them, and printf has a lab demonstrating its use (from J's IDE's menu, go Studio -> Labs... and then look in the System category).
Line 1,187 ⟶ 1,355:
=={{header|Java}}==
Java includes the ''Formatter'' class which includes numerous ways to interpolate text values.<br />
The ''String'' and ''Writer'' classes both implement a form of ''Formatter''.<br /><br />
There are numerous demonstrations on the documentation page on how to apply different interpolations.<br />https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Formatter.html<br /><br />
The format is inspired by the C ''printf'', and is nearly the same except for a few accomodations.<br />
The most idiomatic approach would be to use the ''String.format'' or ''String.formatted'' methods.
<syntaxhighlight lang="java">
String adjective = "little";
String lyric = String.format("Mary had a %s lamb", adjective);
</syntaxhighlight>
<syntaxhighlight lang="java">
String adjective = "little";
String lyric = "Mary had a %s lamb".formatted(adjective);
</syntaxhighlight>
If you wanted to print the string you could use the ''System.out.printf'' method.
<syntaxhighlight lang="java">
String adjective = "little";
System.out.printf("Mary had a %s lamb", adjective);
</syntaxhighlight>
You could also use a combination of ''StringBuilder'' and ''Formatter''.
<syntaxhighlight lang="java">
StringBuilder string = new StringBuilder();
Formatter formatter = new Formatter(string);
String adjective = "little";
formatter.format("Mary had a %s lamb", adjective);
formatter.flush();
</syntaxhighlight>
<br />
Alternately
<syntaxhighlight lang="java">String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); //does not change the original String
Line 1,195 ⟶ 1,391:
//Alternative:
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);</
=={{header|JavaScript}}==
<
var little = "little";
var replaced = original.replace("X", little); //does not change the original string</
Or,
<
var X = "little";
var replaced = `Mary had a ${X} lamb`;</
=={{header|jq}}==
<
| "Mary had a \($x) lamb"</
Any valid jq expression (including a pipeline) can appear between the interpolating parentheses, e.g.:<
The string "Jürgen" has 6 codepoints.</
'''Documentation''': [http://stedolan.github.io/jq/manual/#Stringinterpolationfoo String interpolation]
=={{header|Julia}}==
<
"Mary had a $X lamb"</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,234 ⟶ 1,430:
// it must be treated as an expression
println("Mary had a ${s}r lamb") // not $sr
}</
{{out}}
Line 1,244 ⟶ 1,440:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def original Mary had a X lamb}
-> original
Line 1,251 ⟶ 1,447:
{S.replace X by {Y} in {original}}
-> Mary had a little lamb
</syntaxhighlight>
=={{header|Lasso}}==
Lasso doesn't really have built-in string interpolation, but you can use the built-in email mail-merge capability:
<
{{out}}
<pre>Mary had a little lamb</pre>
Line 1,261 ⟶ 1,457:
=={{header|LiveCode}}==
Livecode has a [http://docs.runrev.com/Function/merge merge] function for interpolation
<
put merge("Mary had a [[str]] lamb.")
-- Mary had a little lamb.</
=={{header|Lua}}==
Line 1,272 ⟶ 1,468:
There is no default support for automatic interpolation of variables names being used as placeholders within a string. However, interpolation is easily emulated by using the [string.gsub] function:
<
print( str )</
or using [string.format] function like C:
<
str2 = ( "Mary had a %s lamb." ):format( "little" )
print( str1, str2 )</
=== Literal characters ===
Line 1,285 ⟶ 1,481:
Interpolation of literal characters escape sequences does occur within a string:
<
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
module checkit {
size$="little"
Line 1,302 ⟶ 1,498:
}
checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
StringReplace["Mary had a X lamb.", {"X" -> Extra}]
->"Mary had a little lamb."</
=={{header|Maxima}}==
<
=={{header|Neko}}==
<
<doc><h2>String interpolation, in Neko</h2>
<p><a href="https://nekovm.org/doc/view/string/">NekoVM String Library</a></p>
Line 1,321 ⟶ 1,517:
var sprintf = $loader.loadprim("std@sprintf", 2)
$print(sprintf("Mary had a %s lamb\n", "little"))</
{{out}}
Line 1,330 ⟶ 1,526:
=={{header|Nemerle}}==
Nemerle has a few ways to accomplish this. It provides an implementation of '''printf()''', $ interpolation within the '''print()''' method, and the most general use is $ interpolation within $ quoted strings.
<
using System.Console;
using Nemerle.IO; // contains printf() and print()
Line 1,343 ⟶ 1,539:
WriteLine($"Mary had a $extra lamb.");
}
}</
=={{header|NetRexx}}==
The Built In Functions (BIFs) of [[NetRexx]] can be employed to manipulate strings quite successfully but for more flexible string interpolation a function package like Java's MessageFormat should be used.
<
options replace format comments java crossref savelog symbols
Line 1,382 ⟶ 1,578:
return
</syntaxhighlight>
{{out}}
<pre style="height: 5ex; overflow:scroll;">
Line 1,392 ⟶ 1,588:
Nim offers two methods to build a string with interpolation.
The first one uses the procedure <code>format</code> or the operator <code>%</code>. Note that with the procedure, an implicit conversion of the arguments is done. With the operator, the conversion must be explicit, using for instance the <code>$</code> operator.
<
var str = "little"
echo "Mary had a $# lamb".format(str)
echo "Mary had a $# lamb" % [str]
# Note: doesn't need an array for a single substitution, but uses an array for multiple substitutions.</
The second method allows to place the expressions directly in the string. There is also two forms, one using the prefix "fmt", the other using the prefix "&". The second form must be used if the string contains newline characters.
<
var str: string = "little"
echo fmt"Mary had a {str} lamb"
echo &"Mary had a {str} lamb"</
=={{header|OCaml}}==
The OCaml standard library provides the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Printf.html Printf]:
<
Printf.printf "Mary had a %s lamb." extra</
Another option is to use compiler plugin mechanism and [https://opam.ocaml.org/packages/ppx_string_interpolation/ ppx_string_interpolation]:
<
let extra = "little" in
[%string "Mary had a $extra lamb."]
</syntaxhighlight>
=={{header|OOC}}==
In a String all expressions between #{...} will be evaluated.
<
main: func {
X := "little"
"Mary had a #{X} lamb" println()
}
</syntaxhighlight>
=={{header|Oz}}==
String interpolation is unidiomatic in Oz. Instead, "virtual strings" are used. [http://www.mozart-oz.org/documentation/op/node4.html Virtual strings] are tuples of printable values and are supported by many library functions.
<
X = "little"
in
{System.showInfo "Mary had a "#X#" lamb"}</
=={{header|PARI/GP}}==
The Pari library has string interpolation, which extends C's:
<
string_interpolate(GEN n)
{
pari_printf("The value was: %Ps.\n", n);
GEN s = pari_sprintf("Storing %Ps in a string", n);
}</
{{works with|PARI/GP|version 2.4.4 and above}}
GP can also interpolate strings:
<
printf("The value was: %Ps", 1<<20);</
=={{header|Perl}}==
<
print "Mary had a $extra lamb.\n";
printf "Mary had a %s lamb.\n", $extra;</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<span style="color: #004080;">string</span> <span style="color: #000000;">size</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"little"</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Mary had a %s lamb."</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">size</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</
{{out}}
<pre>
"Mary had a little lamb."
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_interpolation_(included)
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
"big" var s
( "Mary had a " s " lamb" ) lprint nl
"little" var s
( "Mary had a " s " lamb" ) lprint
</syntaxhighlight>
{{out}}
<pre>Mary had a big lamb
Mary had a little lamb
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?></
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
V = "little",
printf("Mary had a %w lamb\n", V),
% As a function
S = to_fstring("Mary had a %w lamb", V),
println(S).</syntaxhighlight>
=={{header|PicoLisp}}==
<
(prinl (text "Mary had a @1 lamb." Extra)) )</
=={{header|PL/I}}==
<
sit: Proc Options(main);
/*********************************************************************
Line 1,511 ⟶ 1,736:
Return(res);
End;
End;</
{{out}}
<pre>
Line 1,519 ⟶ 1,744:
=={{header|PowerShell}}==
Using the format (-f) operator:
<
"Mary had a {0} lamb." -f $extra</
Using format string with the WriteLine static method
<
[console]::writeline("Mary had a {0} lamb.", $extra)</
Using the format method of the string type
<
[string]::Format("Mary had a {0} lamb.", $extra)</
Note: numeric and date/time formats can be specified with {index:formatString} (i.e. {0:###,###})
=={{header|Prolog}}==
<
format('Mary had a ~w lamb.', [Extra]), % display result
format(atom(Atom), 'Mary had a ~w lamb.', [Extra]). % ... or store it a variable</
Using [http://www.swi-prolog.org/pack/list?p=func library(func)] for SWI-Prolog:
<
Atom = 'Mary had a ~w lamb' $ Extra.</
Using [http://www.swi-prolog.org/pack/list?p=interpolate library(interpolate)] for SWI-Prolog:
<
Atom = 'Mary had a $Extra lamb'.</
=={{header|PureBasic}}==
The function [http://www.purebasic.com/documentation/string/replacestring.html ReplaceString()] is built-in and can have both constants and variables as parameters.
<
''' Implemented in a program context
<
Define txt$, txtvar.s="little"
Line 1,566 ⟶ 1,791:
Mary:
Data.s "Mary had a X lamb."
EndDataSection</
=={{header|Python}}==
Line 1,572 ⟶ 1,797:
Using the % [http://docs.python.org/library/stdtypes.html#string-formatting-operations string interpolation operator]:
<
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'</
Using the [http://docs.python.org/library/string.html#string-formatting .format method of strings]:
<
>>> extra = 'little'
>>> original.format(**locals())
'Mary had a little lamb.'</
Using the format method, but replace by an expressions position as an argument to the format method call instead of by name:
<
>>> extra = 'little'
>>> original.format(extra)
'Mary had a little lamb.'</
Using the [http://docs.python.org/library/string.html#template-strings Template] class of the string module:
<
>>> original = Template('Mary had a $extra lamb.')
>>> extra = 'little'
>>> original.substitute(**locals())
'Mary had a little lamb.'</
Using the new [https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498 f-strings] string literal available from Python 3.6:
<
>>> f'Mary had a {extra} lamb.'
'Mary had a little lamb.'
>>> </
=={{header|Quackery}}==
'''The Task'''
Quackery does not have built-in string interpolation.
'''Not The Task'''
<code>interpolate$</code> replaces every instance of a specified character in a string with a specified string.
Note that the specified string should not include the specified character as this will cause <code>interpolate$</code> to loop indefinitely.
<syntaxhighlight lang="Quackery"> [ stack ] is int.chr
[ stack ] is int.str
[ int.str put
int.chr put
[] swap witheach
[ dup int.chr share = if
[ drop int.str share ]
join ]
int.str release
int.chr release ] is interpolate$ ( $ n $ --> $ )
$ "Mary had a lamb." char X $ "little" interpolate$ echo$ cr
$ "Mary had a X lamb." char X $ "little" interpolate$ echo$ cr
$ "Mary had a X X lamb." char X $ "little" interpolate$ echo$ cr</syntaxhighlight>
{{out}}
<pre>Mary had a lamb.
Mary had a little lamb.
Mary had a little little lamb.
</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
DefStr S
' Qbasic /QuickBasic MID$ statement needs that string2 and substring
' to replace in string1 must have the same length,
' otherwise it overwrites the following part of string1
String1 = "Mary has a X lamb"
Print String1, "Original String1"
Print "Interpolation of string by MID$ statement"
String2 = "little"
Mid$(String1, InStr(String1, "X")) = String2
Print String1
String1 = "Mary has a X lamb"
String2 = "@"
Mid$(String1, InStr(String1, "X")) = String2
Print String1
Print "Interpolation by string's functions"
String1 = "Mary has a X lamb"
String2 = "little"
String1 = Mid$(String1, 1, InStr(String1, "X") - 1) + String2 + Mid$(String1, InStr(String1, "X") + 1, Len(String1) - InStr(String1, "X"))
Print String1, "by MID$"
String1 = "Mary has a X lamb"
String2 = "#§[]@"
String1 = Left$(String1, InStr(String1, "X") - 1) + String2 + Right$(String1, Len(String1) - InStr(String1, "X") + 1)
Print String1, "by LEFT$ and RIGHT$"
</syntaxhighlight>
=={{header|Racket}}==
Line 1,605 ⟶ 1,896:
See the documentation on [http://docs.racket-lang.org/reference/Writing.html?q=printf#%28def._%28%28quote._~23~25kernel%29._fprintf%29%29 fprintf] for more information on string interpolation in Racket.
<
#lang racket
(format "Mary had a ~a lamb" "little")
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say "Mary had a $extra lamb"; # variable interpolation
say "Mary had a { $extra } lamb"; # expression interpolation
Line 1,619 ⟶ 1,910:
say $extra.fmt("Mary had a %s lamb"); # inside-out printf
my @lambs = <Jimmy Bobby Tommy>;
say Q :array { $$$ The lambs are called @lambs[]\\\.} # only @-sigiled containers are interpolated</
=={{header|REBOL}}==
<
size: "little"
build-markup str
Line 1,628 ⟶ 1,919:
;REBOL3 also has the REWORD function
str: "Mary had a $size lamb"
reword str [size "little"]</
=={{header|REXX}}==
Line 1,635 ⟶ 1,926:
<br>However, interpolation can be emulated using the '''changestr''' function:
<
/*the string to be replaced is */
replace = "little" /*usually a unique character(s) */
Line 1,661 ⟶ 1,952:
say 'original4 =' original4
say 'replaced4 =' new3
/*stick a fork in it, we're done.*/</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]].
<br><br>'''output'''
Line 1,679 ⟶ 1,970:
=={{header|Ring}}==
<
aString =substr("Mary had a X lamb.", "X", "little")
see aString + nl
</syntaxhighlight>
An alternate approach using the print() function:
<syntaxhighlight lang="ring">
extra = "little"
print("Mary had a #{extra} lamb.\n")
</syntaxhighlight>
=={{header|Ruby}}==
<
=> "little"
irb(main):002:0> "Mary had a #{extra} lamb."
=> "Mary had a little lamb."
irb(main):003:0> "Mary had a %s lamb." % extra
=> "Mary had a little lamb."</
Documentation:
Line 1,698 ⟶ 1,995:
=={{header|Run BASIC}}==
<
a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X")
print a$
</syntaxhighlight>
=={{header|Rust}}==
Rust has very powerful string interpolation. [https://doc.rust-lang.org/beta/std/fmt/ Documentation here.]
<
println!("Mary had a {} lamb", "little");
// You can specify order
Line 1,710 ⟶ 2,008:
// Or named arguments if you prefer
println!("{name} had a {adj} lamb", adj="little", name="Mary");
}</
=={{header|Scala}}==
{{libheader|Scala}}
<
import util.matching.Regex._
Line 1,763 ⟶ 2,061:
println("Split : " + "Mary had a ${x} lamb.".split("""\$\{([^}]+)\}""").mkString(size))
}
}</
Documentation:
* Scala 2.10.0: [http://docs.scala-lang.org/overviews/core/string-interpolation.html string interpolation]
=={{header|Sed}}==
<
# Usage example: . interpolate "Mary has a X lamb" "quite annoying"
echo "$1" | sed "s/ X / $2 /g"</
=={{header|Seed7}}==
<
const proc: main is func
Line 1,783 ⟶ 2,081:
replaced := replace(original, "X", little);
writeln(replaced);
end func;</
{{out}}
Line 1,792 ⟶ 2,090:
=={{header|SenseTalk}}==
SenseTalk does string interpolation through the <code>merge</code> function, which can evaluate any sort of embedded expression, including entire sections of code like conditionals or repeat loops. For convenience, the merge function can be invoked by simply using a <code>!</code> before a string literal (this is needed because string literals are actually literal in SenseTalk -- there are no characters with hidden meaning by default).
<
put "Mary had a [[x]] lamb." -- this is a literal string
Line 1,799 ⟶ 2,097:
put !"[[repeat with n=2 to 6]]Mary had [[n]] [[x]] lambs.[[return]][[end repeat]]"
put !"Mary had [[repeat with n=2 to 6]][[n]] [[x]] [[end repeat]]lambs."
</syntaxhighlight>
{{out}}
<pre>
Line 1,815 ⟶ 2,113:
=={{header|Sidef}}==
<
say "Mary had a #{extra} lamb";</
or:
<
See: [https://github.com/trizen/sidef/wiki#strings documentation]
=={{header|Slope}}==
<syntaxhighlight lang="slope">(define str "little")
(display (string-format "Mary had a %v lamb." str))</syntaxhighlight>
[https://slope.colorfield.space/slope/api-reference.html#string-format Documentation].
=={{header|SNOBOL4}}==
Every statement in SNOBOL can is a subset of pattern replacement having a subject (s1 in this case), object (s2), and replacement (s3).
<
s2 = "humongous"
s3 = "little"
s1 s2 = s3
end</
See [ftp://ftp.cs.arizona.edu/snobol/gb.pdf The SNOBOL4 Programming Language; Griswold, Poage, Polonsky; Chapter 2 Pattern Matching]
Line 1,835 ⟶ 2,140:
See '''[https://www.stata.com/help.cgi?mf_printf printf]''' in Stata help.
<
Mary had a little lamb.</
=={{header|Swift}}==
<
println("Mary had a \(extra) lamb.")</
=={{header|Tailspin}}==
String interpolation is the normal way to create strings in Tailspin, see '''[https://github.com/tobega/tailspin-v0/blob/master/TailspinReference.md#string-literal string literal]''' in the Tailspin reference
<
def size: 'little';
'Mary had a $size; lamb' -> !OUT::write
</syntaxhighlight>
=={{header|Tcl}}==
String interpolation is a fundamental operation of the Tcl language itself, and is carried out in a <tt>"</tt>double-quoted<tt>"</tt> program strings as well as bare-words. Thus, interpolation of the string from a variable is carried out with the <tt>$</tt> syntax and the string result of a command is interpolated with the <tt>[…]</tt> syntax.
<
puts "Mary had a $size lamb."
Line 1,857 ⟶ 2,162:
lindex $args [expr {int(rand()*[llength $args])}]
}
puts "Mary had a [RandomWord little big] lamb."</
When more sophisticated control is required the <code>format</code> command can be used, which is very similar to the standard [[C]] library's <code>sprintf</code> function:
<
A third approach is to use <code>string map</code>.
<
puts [string map {@SIZE@ "miniscule"} $s]</
Tcl also supports variable variable names. Even more powerful is nested interpolation with the <tt>subst</tt> command.
<
set daddy myself; set mommy {lil' bro}
set fun1 \[string\ to
Line 1,873 ⟶ 2,178:
set middle upper
set fun3 {aNd]}
puts [subst "$grandpa $fun1$[subst $$fun2] $fun3 $grandma"]</
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
MainModule: {
size: "little",
_start: (λ
// Transd supports direct interpolation
(with s String("Mary had a " size " lamb.")
(lout s))
// To interpolate a string variable within another
// string variable we use 'replace'
(with s "Mary had a %s lamb."
(lout (replace s "%s" size)))
)
}</syntaxhighlight>
{{out}}
<pre>
Mary had a little lamb.
Mary had a little lamb.
</pre>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
Line 1,888 ⟶ 2,216:
PRINT sentence_old
PRINT sentence_new
</syntaxhighlight>
{{out}}
<pre>
Line 1,899 ⟶ 2,227:
Within the Unix shell, interpolation only occurs within doublequotes. Strings enclosed in singlequotes will not be subject to interpolation. Note that within the shell, a string may be used bare. If this is done each word within the string is treated separately, and any variable references or escape sequences will be substituted for their values:
<
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra</
A ''parameter substitution'', like <code>$extra</code> or <code>${extra}</code>, interpolates its value into some string. This happens outside quotes or inside "double quotes". The other form of interpolation is [http://www.openbsd.org/cgi-bin/man.cgi?query=printf&apropos=0&sektion=1&manpath=OpenBSD+Current&arch=i386&format=html printf(1)] with <code>%s</code>.
Line 1,909 ⟶ 2,237:
==={{header|C Shell}}===
<
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra</
C Shell has <code>$extra</code> and <code>${extra}</code>. There are also modifiers, like <code>$file:t</code>; [http://www.openbsd.org/cgi-bin/man.cgi?query=csh&apropos=0&sektion=1&manpath=OpenBSD+Current&arch=i386&format=html csh(1) manual] explains those.
Line 1,918 ⟶ 2,246:
=={{header|Ursala}}==
Expressions like this
<
evaluate to a list of character strings beginning with <code>foo</code> and ending
with <code>bar</code>, where <code>foo</code> and <code>bar</code> are literal text (possibly multiple lines)
and <code>x</code> is any expression evaluating to a list of character
strings. Using a dot like this
<
makes it a function returning a list of character strings consisting
of the output from the function <code>f</code> bracketed by the literal text <code>foo</code>
and <code>bar</code>. In this task, the identity function, <code>~&</code>, is used for <code>f</code>.
<
#show+
main = -[Mary had a -[. ~& ]- lamb.]- x</
These operators are parsed like parentheses.
{{out}}
Line 1,939 ⟶ 2,267:
=={{header|Vala}}==
<
string size = "little";
print(@"Mary had a $size lamb\n");
stdout.printf("Mary had a %s lamb\n", size);
}</
{{out}}
Line 1,983 ⟶ 2,311:
=={{header|Verbexx}}==
<
//
// The @INTERPOLATE verb processes a string with imbedded blocks of code. The code
Line 1,997 ⟶ 2,325:
@SAY (@INTERPOLATE "Mary had a { v } lamb");
// output: Mary had a litle lamb</
=={{header|Visual Basic .NET}}==
<
Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)
</syntaxhighlight>
=={{header|Wren}}==
<
var t = "Mary had a %(s) lamb"
System.print(t)</
{{out}}
Line 2,017 ⟶ 2,345:
Mary had a little lamb
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
txt := "little"
str := "Mary had a $txt lamb"
println(str)
</syntaxhighlight>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">char X;
[X:= "little";
Text(0, "Mary had a "); Text(0, X); Text(0, " lamb.");
]</syntaxhighlight>
=={{header|zkl}}==
<
Generates a new string. For more info, refer to manual in the downloads section of [http://zenkinetic.com/ zenkinetic.com zkl page]
Line 2,026 ⟶ 2,367:
{{omit from|8086 Assembly}}
{{omit from|80386 Assembly}}
{{omit from|Axe}}
{{omit from|bc|No built-in string interpolation in bc}}
{{omit from|dc|No built-in string interpolation in dc}}
{{omit from|GUISS}}
{{omit from|Microsoft Small Basic}}
{{omit from|Unlambda|Does not have built-in string interpolatiopn (or built-in strings, for that matter).}}
{{omit from|Z80 Assembly}}
|