String interpolation (included): Difference between revisions

m
→‎{{header|Phix}}: use pygments
m (→‎{{header|Phix}}: use pygments)
 
(84 intermediate revisions by 45 users not shown)
Line 1:
{{Task|Basic language learning}}[[Category:String manipulation]][[Category:Simple]]
[[Category:String manipulation]]
[[Category:Simple]]
[[Category:Strings]]
{{basic data operation}}
{{omit from|NSIS}}{{omit from|BBC BASIC}}
{{omit from|BBC BASIC}}
 
Given a string and defined variables or values, [[wp:String literal#Variable_interpolation|string interpolation]] is the replacement of defined character sequences in the string by values or variable values.
: For example, given an original string of <code>"Mary had a X lamb."</code>, a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string <code>"Mary had a big lamb"</code>.
Line 7 ⟶ 12:
:(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
 
 
;The task is to:
;Task:
# Use your languages inbuilt string interpolation abilities to interpolate a string missing the text <code>"little"</code> which is held in a variable, to produce the output string <code>"Mary had a little lamb"</code>.
# If possible, give links to further documentation on your languages string interpolation features.
 
 
<small>Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.</small>
 
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">V extra = ‘little’
print(‘Mary had a ’extra‘ lamb.’)
print(‘Mary had a #. lamb.’.format(extra))
print(f:‘Mary had a {extra} lamb.’)</syntaxhighlight>
 
{{out}}
<pre>
Mary had a little lamb.
Mary had a little lamb.
Mary had a little lamb.
</pre>
 
=={{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 */
/* In assembler, there is no function to insert a chain */
/* so this program offers two functions to insert */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
.equ CHARPOS, '@'
 
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szString: .asciz " string "
szString1: .asciz "insert"
szString2: .asciz "abcd@efg"
szString3: .asciz "abcdef @"
szString4: .asciz "@ abcdef"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
 
ldr x0,qAdrszString // string address
ldr x1,qAdrszString1 // string address
mov x2,#0
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
ldr x0,qAdrszString // string address
ldr x1,qAdrszString1 // string address
mov x2,#3
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
ldr x0,qAdrszString // string address
ldr x1,qAdrszString1 // string address
mov x2,#40
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
ldr x0,qAdrszString2 // string address
ldr x1,qAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
ldr x0,qAdrszString3 // string address
ldr x1,qAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
 
ldr x0,qAdrszString4 // string address
ldr x1,qAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
qAdrszString1: .quad szString1
qAdrszString2: .quad szString2
qAdrszString3: .quad szString3
qAdrszString4: .quad szString4
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* insertion of a sub-chain in a chain in the desired position */
/******************************************************************/
/* x0 contains the address of string 1 */
/* x1 contains the address of string to insert */
/* x2 contains the position of insertion :
0 start string
if x2 > lenght string 1 insert at end of string*/
/* x0 return the address of new string on the heap */
strInsert:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,#0 // length counter
1: // compute length of string 1
ldrb w4,[x0,x3]
cmp w4,#0
cinc x3,x3,ne // increment to one if not equal
bne 1b // loop if not equal
mov x5,#0 // length counter insertion string
2: // compute length of insertion string
ldrb w4,[x1,x5]
cmp x4,#0
cinc x5,x5,ne // increment to one if not equal
bne 2b
cmp x5,#0
beq 99f // string empty -> error
add x3,x3,x5 // add 2 length
add x3,x3,#1 // +1 for final zero
mov x6,x0 // save address string 1
mov x0,#0 // allocation place heap
mov x8,BRK // call system 'brk'
svc #0
mov x5,x0 // save address heap for output string
add x0,x0,x3 // reservation place x3 length
mov x8,BRK // call system 'brk'
svc #0
cmp x0,#-1 // allocation error
beq 99f
//
mov x8,#0 // index load characters string 1
cmp x2,#0 // index insertion = 0
beq 5f // insertion at string 1 begin
3: // loop copy characters string 1
ldrb w0,[x6,x8] // load character
cmp w0,#0 // end string ?
beq 5f // insertion at end
strb w0,[x5,x8] // store character in output string
add x8,x8,#1 // increment index
cmp x8,x2 // < insertion index ?
blt 3b // yes -> loop
5:
mov x4,x8 // init index character output string
mov x3,#0 // index load characters insertion string
6:
ldrb w0,[x1,x3] // load characters insertion string
cmp w0,#0 // end string ?
beq 7f
strb w0,[x5,x4] // store in output string
add x3,x3,#1 // increment index
add x4,x4,#1 // increment output index
b 6b // and loop
7:
ldrb w0,[x6,x8] // load other character string 1
strb w0,[x5,x4] // store in output string
cmp x0,#0 // end string 1 ?
beq 8f // yes -> end
add x4,x4,#1 // increment output index
add x8,x8,#1 // increment index
b 7b // and loop
8:
mov x0,x5 // return output string address
b 100f
99: // error
mov x0,#-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret
/******************************************************************/
/* insert string at character insertion */
/******************************************************************/
/* x0 contains the address of string 1 */
/* x1 contains the address of insertion string */
/* x0 return the address of new string on the heap */
/* or -1 if error */
strInsertAtChar:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,#0 // length counter
1: // compute length of string 1
ldrb w4,[x0,x3]
cmp w4,#0
cinc x3,x3,ne // increment to one if not equal
bne 1b // loop if not equal
mov x5,#0 // length counter insertion string
2: // compute length to insertion string
ldrb w4,[x1,x5]
cmp x4,#0
cinc x5,x5,ne // increment to one if not equal
bne 2b // and loop
cmp x5,#0
beq 99f // string empty -> error
add x3,x3,x5 // add 2 length
add x3,x3,#1 // +1 for final zero
mov x6,x0 // save address string 1
mov x0,#0 // allocation place heap
mov x8,BRK // call system 'brk'
svc #0
mov x5,x0 // save address heap for output string
add x0,x0,x3 // reservation place x3 length
mov x8,BRK // call system 'brk'
svc #0
cmp x0,#-1 // allocation error
beq 99f
mov x2,0
mov x4,0
3: // loop copy string begin
ldrb w3,[x6,x2]
cmp w3,0
beq 99f
cmp w3,CHARPOS // insertion character ?
beq 5f // yes
strb w3,[x5,x4] // no store character in output string
add x2,x2,1
add x4,x4,1
b 3b // and loop
5: // x4 contains position insertion
add x8,x4,1 // init index character output string
// at position insertion + one
mov x3,#0 // index load characters insertion string
6:
ldrb w0,[x1,x3] // load characters insertion string
cmp w0,#0 // end string ?
beq 7f // yes
strb w0,[x5,x4] // store in output string
add x3,x3,#1 // increment index
add x4,x4,#1 // increment output index
b 6b // and loop
7: // loop copy end string
ldrb w0,[x6,x8] // load other character string 1
strb w0,[x5,x4] // store in output string
cmp x0,#0 // end string 1 ?
beq 8f // yes -> end
add x4,x4,#1 // increment output index
add x8,x8,#1 // increment index
b 7b // and loop
8:
mov x0,x5 // return output string address
b 100f
99: // error
mov x0,#-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret
 
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
CHAR ARRAY extra="little"
 
PrintF("Mary had a %S lamb.%E",extra)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_interpolation_(included).png Screenshot from Atari 8-bit computer]
<pre>
Mary had a little lamb.
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Fixed, Ada.Text_IO;
use Ada.Strings, Ada.Text_IO;
procedure String_Replace is
Line 24 ⟶ 320:
Put_Line (Fixed.Replace_Slice (
Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;</langsyntaxhighlight>
 
Alternatively
 
<langsyntaxhighlight Adalang="ada">Put_Line ("Mary had a " & New_Str & " lamb.");</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">const little = "little"
printf ("Mary had a %s lamb\n", little)
 
// alternatively
println ("Mary had a " + little + " lamb")</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 45 ⟶ 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.
<langsyntaxhighlight lang="algol68">main:(
# as a STRING #
STRING extra = "little";
Line 56 ⟶ 352:
# or: use simply use STRING concatenation #
print(("Mary had a "+extra+" lamb.", new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 63 ⟶ 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 */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BRK, 0x2d @ Linux syscall
.equ CHARPOS, '@'
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szString: .asciz " string "
szString1: .asciz "insert"
szString2: .asciz "abcd@efg"
szString3: .asciz "abcdef @"
szString4: .asciz "@ abcdef"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
ldr r0,iAdrszString // string address
ldr r1,iAdrszString1 // string address
mov r2,#0
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszString // string address
ldr r1,iAdrszString1 // string address
mov r2,#3
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszString // string address
ldr r1,iAdrszString1 // string address
mov r2,#40
bl strInsert //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszString2 // string address
ldr r1,iAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszString3 // string address
ldr r1,iAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
ldr r0,iAdrszString4 // string address
ldr r1,iAdrszString1 // string address
bl strInsertAtChar //
// return new pointer
bl affichageMess // display result string
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov r0, #0 // return code
mov r7, #EXIT // request to exit program
svc 0 // perform the system call
iAdrszString: .int szString
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString3
iAdrszString4: .int szString4
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* insertion of a sub-chain in a chain in the desired position */
/******************************************************************/
/* r0 contains the address of string 1 */
/* r1 contains the address of string to insert */
/* r2 contains the position of insertion :
0 start string
if r2 > lenght string 1 insert at end of string*/
/* r0 return the address of new string on the heap */
strInsert:
push {r1-r4,lr} @ save registres
mov r3,#0 // length counter
1: // compute length of string 1
ldrb r4,[r0,r3]
cmp r4,#0
addne r3,r3,#1 // increment to one if not equal
bne 1b // loop if not equal
mov r5,#0 // length counter insertion string
2: // compute length of insertion string
ldrb r4,[r1,r5]
cmp r4,#0
addne r5,r5,#1 // increment to one if not equal
bne 2b
cmp r5,#0
beq 99f // string empty -> error
add r3,r3,r5 // add 2 length
add r3,r3,#1 // +1 for final zero
mov r6,r0 // save address string 1
mov r0,#0 // allocation place heap
mov r7,#BRK // call system 'brk'
svc #0
mov r5,r0 // save address heap for output string
add r0,r0,r3 // reservation place r3 length
mov r7,#BRK // call system 'brk'
svc #0
cmp r0,#-1 // allocation error
beq 99f
//
mov r7,#0 // index load characters string 1
cmp r2,#0 // index insertion = 0
beq 5f // insertion at string 1 begin
3: // loop copy characters string 1
ldrb r0,[r6,r7] // load character
cmp r0,#0 // end string ?
beq 5f // insertion at end
strb r0,[r5,r7] // store character in output string
add r7,r7,#1 // increment index
cmp r7,r2 // < insertion index ?
blt 3b // yes -> loop
5:
mov r4,r7 // init index character output string
mov r3,#0 // index load characters insertion string
6:
ldrb r0,[r1,r3] // load characters insertion string
cmp r0,#0 // end string ?
beq 7f
strb r0,[r5,r4] // store in output string
add r3,r3,#1 // increment index
add r4,r4,#1 // increment output index
b 6b // and loop
7:
ldrb r0,[r6,r7] // load other character string 1
strb r0,[r5,r4] // store in output string
cmp r0,#0 // end string 1 ?
beq 8f // yes -> end
add r4,r4,#1 // increment output index
add r7,r7,#1 // increment index
b 7b // and loop
8:
mov r0,r5 // return output string address
b 100f
99: // error
mov r0,#-1
100:
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* insert string at character insertion */
/******************************************************************/
/* r0 contains the address of string 1 */
/* r1 contains the address of insertion string */
/* r0 return the address of new string on the heap */
/* or -1 if error */
strInsertAtChar:
push {r1-r7,lr} @ save registres
mov r3,#0 // length counter
1: // compute length of string 1
ldrb r4,[r0,r3]
cmp r4,#0
addne r3,r3,#1 // increment to one if not equal
bne 1b // loop if not equal
mov r5,#0 // length counter insertion string
2: // compute length to insertion string
ldrb r4,[r1,r5]
cmp r4,#0
addne r5,r5,#1 // increment to one if not equal
bne 2b // and loop
cmp r5,#0
beq 99f // string empty -> error
add r3,r3,r5 // add 2 length
add r3,r3,#1 // +1 for final zero
mov r6,r0 // save address string 1
mov r0,#0 // allocation place heap
mov r7,#BRK // call system 'brk'
svc #0
mov r5,r0 // save address heap for output string
add r0,r0,r3 // reservation place r3 length
mov r7,#BRK // call system 'brk'
svc #0
cmp r0,#-1 // allocation error
beq 99f
mov r2,#0
mov r4,#0
3: // loop copy string begin
ldrb r3,[r6,r2]
cmp r3,#0
beq 99f
cmp r3,#CHARPOS // insertion character ?
beq 5f // yes
strb r3,[r5,r4] // no store character in output string
add r2,r2,#1
add r4,r4,#1
b 3b // and loop
5: // r4 contains position insertion
add r7,r4,#1 // init index character output string
// at position insertion + one
mov r3,#0 // index load characters insertion string
6:
ldrb r0,[r1,r3] // load characters insertion string
cmp r0,#0 // end string ?
beq 7f // yes
strb r0,[r5,r4] // store in output string
add r3,r3,#1 // increment index
add r4,r4,#1 // increment output index
b 6b // and loop
7: // loop copy end string
ldrb r0,[r6,r7] // load other character string 1
strb r0,[r5,r4] // store in output string
cmp r0,#0 // end string 1 ?
beq 8f // yes -> end
add r4,r4,#1 // increment output index
add r7,r7,#1 // increment index
b 7b // and loop
8:
mov r0,r5 // return output string address
b 100f
99: // error
mov r0,#-1
100:
pop {r1-r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
insert string
stinsertring
string insert
abcdinsertefg
abcdef insert
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}}==
<syntaxhighlight lang="rebol">sizeOfLamb: "little"
 
print ~"Mary had a |sizeOfLamb| lamb."</syntaxhighlight>
 
{{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}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Using the = operator
LIT = little
string = Mary had a %LIT% lamb.
Line 72 ⟶ 708:
string := "Mary had a" LIT " lamb."
 
MsgBox %string%</langsyntaxhighlight>
 
Documentation: [http://www.autohotkey.com/docs/Variables.htm#Variables Variables] (see '''Storing values in variables''' and '''Retrieving the contents of variables''')
Line 78 ⟶ 714:
=={{header|AWK}}==
String interpolation is usually done with functions sub() and gsub(). gawk has also gensub().
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
str="Mary had a # lamb."
gsub(/#/, "little", str)
print str
}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
call :interpolate %1 %2 res
Line 96 ⟶ 808:
set str=%~2
set %3=!pat:X=%str%!
goto :eof</langsyntaxhighlight>
 
''Demo''
<langsyntaxhighlight lang="dos">>interpolate.cmd "Mary had a X lamb" little
Mary had a little lamb</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="bracmat">@("Mary had a X lamb":?a X ?z) & str$(!a little !z)</langsyntaxhighlight>
 
=={{header|C}}==
Include the <code><stdio.h></code> header to use the functions of the [[wp:Printf|printf]] family:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main() {
Line 115 ⟶ 838:
printf("Mary had a %s lamb.\n", extra);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
This is called [http://msdn.microsoft.com/en-us/library/txafckwd.aspx "composite formatting"] in MSDN.
 
<syntaxhighlight lang="csharp">class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <iostream>
 
Line 128 ⟶ 864:
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}</syntaxhighlight> =={{header|C++}}==
}</lang>
{{works with|C++11}}
<syntaxhighlight lang="cpp">// Variable argument template
 
#include <string>
=={{header|C sharp|C#}}==
#include <vector>
This is called [http://msdn.microsoft.com/en-us/library/txafckwd.aspx "composite formatting"] in MSDN.
 
using std::string;
<lang csharp>class Program
using std::vector;
 
template<typename S, typename... Args>
string interpolate( const S& orig , const Args&... args)
{
string out(orig);
static void Main()
 
{
// populate vector from argument list
string extra = "little";
auto va = {args...};
string formatted = $"Mary had a {extra} lamb.";
vector<string> v{va};
System.Console.WriteLine(formatted);
}
size_t i = 1;
}</lang>
 
for( string s: v)
{
string is = std::to_string(i);
string t = "{" + is + "}"; // "{1}", "{2}", ...
try
{
auto pos = out.find(t);
 
if ( pos != out.npos) // found token
{
out.erase(pos, t.length()); //erase token
out.insert( pos, s); // insert arg
}
 
i++; // next
}
catch( std::exception& e)
{
std::cerr << e.what() << std::endl;
}
 
} // for
 
return out;
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(let [little "little"]
(println (format "Mary had a %s lamb." little)))</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. interpolation-included.
 
Line 160 ⟶ 928:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|Coco}}==
Line 166 ⟶ 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]:
 
<langsyntaxhighlight lang="coco">size = 'little'
console.log "Mary had a #size lamb."</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
size = 'little'
console.log "Mary had a #{size} lamb." # Mary had a little lamb.
Line 180 ⟶ 948:
Multi-line strings and arbtrary expressions work: #{ 5 * 4 }
"""
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((extra "little"))
(format t "Mary had a ~A lamb.~%" extra))</langsyntaxhighlight>
 
More documentation on the [http://www.cs.cmu.edu/Groups/AI/html/hyperspec/HyperSpec/Body/fun_format.html FORMAT] function.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
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;
}</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb.
Line 201 ⟶ 969:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program Project1;
 
uses
Line 236 ⟶ 1,004:
writeln(Output);
 
end.</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb.
Line 244 ⟶ 1,012:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">PrintLn(Format('Mary had a %s lamb.', ['little']))</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb.</pre>
 
=={{header|Dyalect}}==
 
Dyalect has a built-in [https://github.com/vorov2/dyalect/wiki/String#interpolation string interpolation] feature.
 
<syntaxhighlight lang="dyalect">let lamb_size = "little"
print("Mary had a \(lamb_size) lamb.")</syntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def adjective := "little"
`Mary had a $adjective lamb`</langsyntaxhighlight>
 
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 257 ⟶ 1,032:
The above code is equivalent to (expands into):
 
<langsyntaxhighlight lang="e">def adjective := "little"
simple__quasiParser.valueMaker("Mary had a ${0} lamb").substitute([adjective])</langsyntaxhighlight>
 
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 264 ⟶ 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.
<langsyntaxhighlight lang="scheme">
;; format uses %a or ~a as replacement directive
(format "Mary had a ~a lamb" "little")
Line 270 ⟶ 1,045:
(format "Mary had a %a lamb" "little")
→ "Mary had a little lamb"
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
<lang ECL>
IMPORT STD;
STD.Str.FindReplace('Mary had a X Lamb', 'X','little');
</syntaxhighlight>
</lang>
=={{header|Elena}}==
ELENA 3.2 :
<lang elena>import extensions.
 
=={{header|Elena}}==
program =
ELENA 4.x :
[
<syntaxhighlight lang="elena">import extensions;
var s := "little".
console printLineFormatted("Mary had a {0} lamb.",s); readChar.
public program()
].</lang>
{
var s := "little";
console.printLineFormatted("Mary had a {0} lamb.",s).readChar()
}</syntaxhighlight>
 
=={{header|Elixir}}==
Elixir borrows Ruby's #{...} interpolation syntax.
<langsyntaxhighlight lang="elixir">
x = "little"
IO.puts "Mary had a #{x} lamb"
</syntaxhighlight>
</lang>
 
=={{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 304 ⟶ 1,086:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant lambType = "little"
sequence s
s = sprintf("Mary had a %s lamb.",{lambType})
puts(1,s)</langsyntaxhighlight>
See
[http://openeuphoria.org/docs/std_text.html#_3233_sprintf sprintf],
Line 314 ⟶ 1,096:
=={{header|F_Sharp|F#}}==
[http://msdn.microsoft.com/en-us/library/ee370560(VS.100).aspx Documentation]
<langsyntaxhighlight lang="fsharp">let lambType = "little"
printfn "Mary had a %s lamb." lambType</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: formatting
 
SYMBOL: little
Line 324 ⟶ 1,106:
"little" little set
 
little get "Mary had a %s lamb" sprintf</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="factor">USE: formatting
 
CONSTANT: little "little"
 
little "Mary had a %s lamb" sprintf</langsyntaxhighlight>
 
=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic''
<syntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
 
size = "little"
> @ "Mary had a $size lamb"
 
// line 1: use of the = operator
// line 2: use of the @ and $ operator
</syntaxhighlight>
{{out}}
<pre>
Mary had a little lamb
[Finished in 0.2s]
</pre>
 
=={{header|Fantom}}==
Line 338 ⟶ 1,138:
Interpolating a variable value into a string is done by using a $ prefix on the variable name within a string. For example:
 
<langsyntaxhighlight lang="fantom">
fansh> x := "little"
little
fansh> echo ("Mary had a $x lamb")
Mary had a little lamb
</syntaxhighlight>
</lang>
 
Documentation at: [http://fantom.org/doc/docLang/Literals.html#interpolation Fantom website]
 
=={{header|Forth}}==
 
<syntaxhighlight lang="forth">variable 'src
variable #src
variable 'out
variable #out
 
: Replace~ dup [char] ~ = \ test for escape char
if 'out @ 1+ #out @ type drop \ replace the escape char
else emit \ otherwise write char
then ;
: format 0
begin dup #src @ u<
while 1+ dup 'src @ + c@
replace~
repeat ;
 
\ Test of function
Here 'src ! ," Mary had a ~ lamb" here 'src @ - #src !
page
cr ." Original : "
'src @ 1+ #src @ type
cr ." 1st Replacement : "
here 'out ! ," little" here 'out @ - #out !
format
cr ." 2nd Replacement : "
here 'out ! ," BIG" here 'out @ - #out !
format
</syntaxhighlight>
{{out}}
<pre>
Original : Mary had a ~ lamb
1st Replacement : Mary had a little lamb
2nd Replacement : Mary had a BIG lamb
</pre>
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">program interpolate
 
write (*,*) trim(inter("Mary had a X lamb.","X","little"))
Line 366 ⟶ 1,202:
end function inter
end program interpolate</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 373 ⟶ 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:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "crt/stdio.bi" '' header needed for printf
Line 381 ⟶ 1,217:
x = "little"
printf("Mary also had a %s lamb", x)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 390 ⟶ 1,226:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">x = "little"
println["Mary had a $x lamb."]</langsyntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">X = 'little'
println( "Mary had a $X lamb." )</langsyntaxhighlight>
 
=={{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]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
Print Subst("Mary had a &1 lamb", "little")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 412 ⟶ 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.
<langsyntaxhighlight lang="gastona">#listix#
 
<how> //little
Line 418 ⟶ 1,265:
<main> //Mary @<what>
</syntaxhighlight>
</lang>
{{out|Output}}
<pre>
Line 426 ⟶ 1,273:
=={{header|Go}}==
Doc: [http://golang.org/pkg/fmt/ http://golang.org/pkg/fmt/]
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 439 ⟶ 1,286:
fmt.Println(out)
}
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def adj = 'little'
assert 'Mary had a little lamb.' == "Mary had a ${adj} lamb."</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 449 ⟶ 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.
 
<langsyntaxhighlight lang="haskell">import Text.Printf
 
main = printf "Mary had a %s lamb\n" "little"</langsyntaxhighlight>
 
=={{header|Haxe}}==
{{trans|C#}}
<syntaxhighlight lang="haxe">class Program {
static function main() {
var extra = 'little';
var formatted = 'Mary had a $extra lamb.';
Sys.println(formatted);
}
}</syntaxhighlight>
 
{{out}}
<pre>
Mary had a little lamb.
</pre>
 
=={{header|HicEst}}==
[http://www.HicEst.com/EDIT Further documentation on HicEst string interpolation function EDIT()]
<langsyntaxhighlight lang="hicest">CHARACTER original="Mary had a X lamb", little = "little", output_string*100
 
output_string = original
EDIT(Text=output_string, Right='X', RePLaceby=little)</langsyntaxhighlight>
 
=={{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]
<langsyntaxhighlight Iconlang="icon"> s2 := "humongous"
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</langsyntaxhighlight>
{{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 472 ⟶ 1,334:
=={{header|J}}==
The <code>strings</code> and <code>printf</code> scripts are part of the base library.
<langsyntaxhighlight lang="j"> require 'printf'
'Mary had a %s lamb.' sprintf <'little'
Mary had a little lamb.
Line 480 ⟶ 1,342:
Mary had a little lamb.
'Mary had a %s lamb.' rplc '%s';'little'
Mary had a little lamb.</langsyntaxhighlight>
 
Documentation:
Line 486 ⟶ 1,348:
The comments in these library files give brief descriptions of their contents, and you can browse them using open:
 
<syntaxhighlight lang J="j"> open'strings printf'</langsyntaxhighlight>
 
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 493 ⟶ 1,355:
 
=={{header|Java}}==
Java includes the ''Formatter'' class which includes numerous ways to interpolate text values.<br />
<lang java>String original = "Mary had a X lamb";
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 501 ⟶ 1,391:
//Alternative:
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var original = "Mary had a X lamb";
var little = "little";
var replaced = original.replace("X", little); //does not change the original string</langsyntaxhighlight>
 
Or,
 
<langsyntaxhighlight lang="javascript">// ECMAScript 6
var X = "little";
var replaced = `Mary had a ${X} lamb`;</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">"little" as $x
| "Mary had a \($x) lamb"</langsyntaxhighlight>
 
Any valid jq expression (including a pipeline) can appear between the interpolating parentheses, e.g.:<langsyntaxhighlight lang="jq">$ jq -M -n -r '"Jürgen" as $x | "The string \"\($x)\" has \($x|length) codepoints."'
The string "Jürgen" has 6 codepoints.</langsyntaxhighlight>
'''Documentation''': [http://stedolan.github.io/jq/manual/#Stringinterpolationfoo String interpolation]
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">X = "little"
"Mary had a $X lamb"</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 540 ⟶ 1,430:
// it must be treated as an expression
println("Mary had a ${s}r lamb") // not $sr
}</langsyntaxhighlight>
 
{{out}}
Line 548 ⟶ 1,438:
Mary had a littler lamb
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def original Mary had a X lamb}
-> original
{def Y little}
-> Y
{S.replace X by {Y} in {original}}
-> Mary had a little lamb
</syntaxhighlight>
 
=={{header|langur}}==
All interpolations in langur use double curly braces.
 
<syntaxhighlight lang="langur">val .x = "little"
writeln "Mary had a {{.x}} lamb."</syntaxhighlight>
 
Modifiers follow the interpolated value with a colon.
<syntaxhighlight lang="langur">writeln "Lamb count: {{.x : 7}}"</syntaxhighlight>
 
Modifiers may be chained within a single interpolation.
<syntaxhighlight lang="langur">writeln "Partial lamb count: {{.x : r2 : 10}}"
# rounds to 2 decimal places, then aligns to 10 code points
# (hopefully no partial lambs)
</syntaxhighlight>
 
See https://langurlang.org/features/interpolation/ for more details.
 
=={{header|Lasso}}==
Lasso doesn't really have built-in string interpolation, but you can use the built-in email mail-merge capability:
<langsyntaxhighlight lang="lasso">email_merge("Mary had a #adjective# lamb", map("token"="little", "adjective"=""), null, 'plain')</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb</pre>
 
 
=={{header|LiveCode}}==
Livecode has a [http://docs.runrev.com/Function/merge merge] function for interpolation
<langsyntaxhighlight LiveCodelang="livecode">local str="little"
put merge("Mary had a [[str]] lamb.")
 
-- Mary had a little lamb.</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 569 ⟶ 1,485:
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:
 
<langsyntaxhighlight Lualang="lua">str = string.gsub( "Mary had a X lamb.", "X", "little" )
print( str )</langsyntaxhighlight>
 
or using [string.format] function like C:
<syntaxhighlight lang="lua">str1 = string.format( "Mary had a %s lamb.", "little" )
str2 = ( "Mary had a %s lamb." ):format( "little" )
print( str1, str2 )</syntaxhighlight>
 
=== Literal characters ===
Line 576 ⟶ 1,498:
Interpolation of literal characters escape sequences does occur within a string:
 
<langsyntaxhighlight lang="lua">print "Mary had a \n lamb" -- The \n is interpreted as an escape sequence for a newline</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang Mathematica>Extra = "little";
module checkit {
size$="little"
m$=format$("Mary had a {0} lamb.", size$)
Print m$
Const RightJustify=1
\\ format$(string_expression) process escape codes
Report RightJustify, format$(format$("Mary had a {0} {1} lamb.\r\n We use {0} for size, and {1} for color\r\n", size$, "wh"+"ite"))
\\ we can use { } for multi line string
Report RightJustify, format$({Mary had a {0} {1} lamb.
We use {0} for size, and {1} for color
}, size$, "wh"+"ite")
}
checkit
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Extra = "little";
StringReplace["Mary had a X lamb.", {"X" -> Extra}]
->"Mary had a little lamb."</langsyntaxhighlight>
 
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">printf(true, "Mary had a ~a lamb", "little");</langsyntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<doc><h2>String interpolation, in Neko</h2>
<p><a href="https://nekovm.org/doc/view/string/">NekoVM String Library</a></p>
</doc>
**/
 
var sprintf = $loader.loadprim("std@sprintf", 2)
 
$print(sprintf("Mary had a %s lamb\n", "little"))</syntaxhighlight>
 
{{out}}
<pre>prompt$ nekoc string-interpolation.neko
prompt$ neko string-interpolation.n
Mary had a little lamb</pre>
 
=={{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.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.IO; // contains printf() and print()
Line 602 ⟶ 1,556:
WriteLine($"Mary had a $extra lamb.");
}
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols
Line 641 ⟶ 1,595:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 5ex; overflow:scroll;">
Line 649 ⟶ 1,603:
 
=={{header|Nim}}==
Nim offers two methods to build a string with interpolation.
<lang nim>import strutils
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.
<syntaxhighlight lang="nim">import strutils
 
var str = "little"
echo "Mary had a $# lamb" % [.format(str] )
echo "Mary had a $# lamb" % [str]
# doesn't need an array for one substitution, but use an array for multiple substitutions</lang>
# Note: doesn't need an array for a single substitution, but uses an array for multiple substitutions.</syntaxhighlight>
 
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.
<lang nim>import strformat
 
<syntaxhighlight lang="nim">import strformat
 
var str: string = "little"
echo fmt"Mary had a {str} lamb"
echo &"Mary had a {str} lamb"</langsyntaxhighlight>
 
=={{header|OCaml}}==
The OCaml standard library provides the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Printf.html Printf]:
 
<langsyntaxhighlight lang="ocaml">let extra = "little" in
Printf.printf "Mary had a %s lamb." extra</langsyntaxhighlight>
 
Another option is to use compiler plugin mechanism and [https://opam.ocaml.org/packages/ppx_string_interpolation/ ppx_string_interpolation]:
 
<syntaxhighlight lang="ocaml">
let extra = "little" in
[%string "Mary had a $extra lamb."]
</syntaxhighlight>
 
=={{header|OOC}}==
In a String all expressions between #{...} will be evaluated.
<langsyntaxhighlight lang="ooc">
main: func {
X := "little"
"Mary had a #{X} lamb" println()
}
</syntaxhighlight>
</lang>
 
=={{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.
 
<langsyntaxhighlight lang="oz">declare
X = "little"
in
{System.showInfo "Mary had a "#X#" lamb"}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
The Pari library has string interpolation, which extends C's:
<langsyntaxhighlight Clang="c">GEN
string_interpolate(GEN n)
{
pari_printf("The value was: %Ps.\n", n);
GEN s = pari_sprintf("Storing %Ps in a string", n);
}</langsyntaxhighlight>
 
{{works with|PARI/GP|version 2.4.4 and above}}
GP can also interpolate strings:
<langsyntaxhighlight lang="parigp">s=Strprintf("The value was: %Ps", 1<<20);
printf("The value was: %Ps", 1<<20);</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">$extra = "little";
print "Mary had a $extra lamb.\n";
printf "Mary had a %s lamb.\n", $extra;</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>my $extra = "little";
say "Mary had a $extra lamb"; # variable interpolation
say "Mary had a { $extra } lamb"; # expression interpolation
printf "Mary had a %s lamb.\n", $extra; # standard printf
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</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>string size = "little"
<!--(phixonline)-->
<syntaxhighlight lang="phix">
string size = "little"
string s = sprintf("Mary had a %s lamb.",{size})
?s -- or printf(1,".."".."), probably with a \n
?s</lang>
</syntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="php"><?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?></langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Extra "little"
(prinl (text "Mary had a @1 lamb." Extra)) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLIlang="pli">*process or(!) source xref attributes;
sit: Proc Options(main);
/*********************************************************************
Line 764 ⟶ 1,754:
Return(res);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 772 ⟶ 1,762:
=={{header|PowerShell}}==
Using the format (-f) operator:
<langsyntaxhighlight lang="powershell">$extra = "little"
"Mary had a {0} lamb." -f $extra</langsyntaxhighlight>
 
Using format string with the WriteLine static method
<langsyntaxhighlight lang="powershell">$extra = "little"
[console]::writeline("Mary had a {0} lamb.", $extra)</langsyntaxhighlight>
 
Using the format method of the string type
<langsyntaxhighlight lang="powershell">$extra = "little"
[string]::Format("Mary had a {0} lamb.", $extra)</langsyntaxhighlight>
 
Note: numeric and date/time formats can be specified with {index:formatString} (i.e. {0:###,###})
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">Extra = little,
format('Mary had a ~w lamb.', [Extra]), % display result
format(atom(Atom), 'Mary had a ~w lamb.', [Extra]). % ... or store it a variable</langsyntaxhighlight>
 
Using [http://www.swi-prolog.org/pack/list?p=func library(func)] for SWI-Prolog:
 
<langsyntaxhighlight Prologlang="prolog">Extra = little,
Atom = 'Mary had a ~w lamb' $ Extra.</langsyntaxhighlight>
 
Using [http://www.swi-prolog.org/pack/list?p=interpolate library(interpolate)] for SWI-Prolog:
 
<langsyntaxhighlight Prologlang="prolog">Extra = little,
Atom = 'Mary had a $Extra lamb'.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight PureBasiclang="purebasic">ReplaceString("Mary had a X lamb.","X","little")</langsyntaxhighlight>
''' Implemented in a program context
<langsyntaxhighlight PureBasiclang="purebasic">; String variable can be defined by appending .s to its name during definition or by appending and using $ as a part of its name.
Define txt$, txtvar.s="little"
 
Line 819 ⟶ 1,809:
Mary:
Data.s "Mary had a X lamb."
EndDataSection</langsyntaxhighlight>
 
=={{header|Python}}==
Line 825 ⟶ 1,815:
 
Using the % [http://docs.python.org/library/stdtypes.html#string-formatting-operations string interpolation operator]:
<langsyntaxhighlight lang="python">>>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'</langsyntaxhighlight>
 
Using the [http://docs.python.org/library/string.html#string-formatting .format method of strings]:
<langsyntaxhighlight lang="python">>>> original = 'Mary had a {extra} lamb.'
>>> extra = 'little'
>>> original.format(**locals())
'Mary had a little lamb.'</langsyntaxhighlight>
Using the format method, but replace by an expressions position as an argument to the format method call instead of by name:
<langsyntaxhighlight lang="python">>>> original = 'Mary had a {0} lamb.'
>>> extra = 'little'
>>> original.format(extra)
'Mary had a little lamb.'</langsyntaxhighlight>
 
Using the [http://docs.python.org/library/string.html#template-strings Template] class of the string module:
<langsyntaxhighlight lang="python">>>> from string import Template
>>> original = Template('Mary had a $extra lamb.')
>>> extra = 'little'
>>> original.substitute(**locals())
'Mary had a little lamb.'</langsyntaxhighlight>
 
Using the new [https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498 f-strings] string literal available from Python 3.6:
<langsyntaxhighlight lang="python">>>> extra = 'little'
>>> f'Mary had a {extra} lamb.'
'Mary had a little lamb.'
>>> </langsyntaxhighlight>
 
=={{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 858 ⟶ 1,914:
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.
 
<langsyntaxhighlight lang="racket">
#lang racket
 
(format "Mary had a ~a lamb" "little")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $extra = "little";
say "Mary had a $extra lamb"; # variable interpolation
say "Mary had a { $extra } lamb"; # expression interpolation
printf "Mary had a %s lamb.\n", $extra; # standard printf
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</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">str: "Mary had a <%size%> lamb"
size: "little"
build-markup str
Line 871 ⟶ 1,937:
;REBOL3 also has the REWORD function
str: "Mary had a $size lamb"
reword str [size "little"]</langsyntaxhighlight>
 
 
=={{header|REXX}}==
Line 879 ⟶ 1,944:
<br>However, interpolation can be emulated using the &nbsp; '''changestr''' &nbsp; function:
 
<langsyntaxhighlight lang="rexx">/*REXX program to demonstrate string interpolation (string replacement).*/
/*the string to be replaced is */
replace = "little" /*usually a unique character(s) */
Line 905 ⟶ 1,970:
say 'original4 =' original4
say 'replaced4 =' new3
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>'''output'''
Line 923 ⟶ 1,988:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aString =substr("Mary had a X lamb.", "X", "little")
see aString + nl
</syntaxhighlight>
</lang>
 
An alternate approach using the print() function:
<syntaxhighlight lang="ring">
extra = "little"
print("Mary had a #{extra} lamb.\n")
</syntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">irb(main):001:0> extra = 'little'
=> "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."</langsyntaxhighlight>
 
Documentation:
Line 942 ⟶ 2,013:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">"a$ = Mary had a X lamb."
a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X")
print a$
</lang>
</syntaxhighlight>
 
=={{header|Rust}}==
Rust has very powerful string interpolation. [https://doc.rust-lang.org/beta/std/fmt/ Documentation here.]
<langsyntaxhighlight lang="rust">fn main() {
println!("Mary had a {} lamb", "little");
// You can specify order
Line 954 ⟶ 2,026:
// Or named arguments if you prefer
println!("{name} had a {adj} lamb", adj="little", name="Mary");
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
 
<langsyntaxhighlight Scalalang="scala">object StringInterpolation extends App {
 
import util.matching.Regex._
Line 1,007 ⟶ 2,079:
println("Split : " + "Mary had a ${x} lamb.".split("""\$\{([^}]+)\}""").mkString(size))
}
}</langsyntaxhighlight>
Documentation:
* Scala 2.10.0: [http://docs.scala-lang.org/overviews/core/string-interpolation.html string interpolation]
 
=={{header|Sed}}==
<langsyntaxhighlight lang="bash">#!/bin/bash
# Usage example: . interpolate "Mary has a X lamb" "quite annoying"
echo "$1" | sed "s/ X / $2 /g"</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 1,027 ⟶ 2,099:
replaced := replace(original, "X", little);
writeln(replaced);
end func;</langsyntaxhighlight>
 
{{out}}
<pre>
Mary had a little lamb
</pre>
 
=={{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).
<syntaxhighlight lang="sensetalk">put "little" into x
 
put "Mary had a [[x]] lamb." -- this is a literal string
put !"Mary had a [[x]] lamb." -- this is an interpolated string
put
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>
Mary had a [[x]] lamb.
Mary had a little lamb.
 
Mary had 2 little lambs.
Mary had 3 little lambs.
Mary had 4 little lambs.
Mary had 5 little lambs.
Mary had 6 little lambs.
 
Mary had 2 little 3 little 4 little 5 little 6 little lambs.
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var extra = 'little';
say "Mary had a #{extra} lamb";</langsyntaxhighlight>
 
or:
<langsyntaxhighlight lang="ruby">say ("Mary had a %s lamb" % 'little');</langsyntaxhighlight>
 
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).
<langsyntaxhighlight lang="snobol"> s1 = "Mary had a humongous lamb."
s2 = "humongous"
s3 = "little"
s1 s2 = s3
end</langsyntaxhighlight>
See [ftp://ftp.cs.arizona.edu/snobol/gb.pdf The SNOBOL4 Programming Language; Griswold, Poage, Polonsky; Chapter 2 Pattern Matching]
 
Line 1,055 ⟶ 2,158:
See '''[https://www.stata.com/help.cgi?mf_printf printf]''' in Stata help.
 
<langsyntaxhighlight lang="stata">: printf("Mary had a %s lamb.\n", "little")
Mary had a little lamb.</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">let extra = "little"
println("Mary had a \(extra) lamb.")</langsyntaxhighlight>
 
=={{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
<syntaxhighlight lang="tailspin">
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.
<langsyntaxhighlight lang="tcl">set size "little"
puts "Mary had a $size lamb."
 
Line 1,070 ⟶ 2,180:
lindex $args [expr {int(rand()*[llength $args])}]
}
puts "Mary had a [RandomWord little big] lamb."</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="tcl">puts [format "Mary had a %s %s." [RandomWord little big] [RandomWord lamb piglet calf]]</langsyntaxhighlight>
 
A third approach is to use <code>string map</code>.
<langsyntaxhighlight lang="tcl">set s "Mary had a @SIZE@ lamb."
puts [string map {@SIZE@ "miniscule"} $s]</langsyntaxhighlight>
 
Tcl also supports variable variable names. Even more powerful is nested interpolation with the <tt>subst</tt> command.
<langsyntaxhighlight lang="tcl">set grandpa {$daddy}; set grandma \$mommy
set daddy myself; set mommy {lil' bro}
set fun1 \[string\ to
Line 1,086 ⟶ 2,196:
set middle upper
set fun3 {aNd]}
puts [subst "$grandpa $fun1$[subst $$fun2] $fun3 $grandma"]</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 1,101 ⟶ 2,234:
PRINT sentence_old
PRINT sentence_new
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,112 ⟶ 2,245:
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:
 
<langsyntaxhighlight lang="sh">extra='little'
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra</langsyntaxhighlight>
 
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,122 ⟶ 2,255:
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">set extra='little'
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra</langsyntaxhighlight>
 
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,131 ⟶ 2,264:
=={{header|Ursala}}==
Expressions like this
<langsyntaxhighlight Ursalalang="ursala">-[foo-[ x ]-bar]-</langsyntaxhighlight>
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
<langsyntaxhighlight Ursalalang="ursala">-[foo-[. f ]-bar]-</langsyntaxhighlight>
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>.
<langsyntaxhighlight Ursalalang="ursala">x = <'little'>
 
#show+
 
main = -[Mary had a -[. ~& ]- lamb.]- x</langsyntaxhighlight>
These operators are parsed like parentheses.
{{out}}
<pre>
Mary had a little lamb.
</pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
string size = "little";
print(@"Mary had a $size lamb\n");
stdout.printf("Mary had a %s lamb\n", size);
}</syntaxhighlight>
 
{{out}}
<pre>
Mary had a little lamb
Mary had a little lamb
</pre>
 
Line 1,183 ⟶ 2,329:
 
=={{header|Verbexx}}==
<langsyntaxhighlight lang="verbexx">////////////////////////////////////////////////////////////////////////////////////////
//
// The @INTERPOLATE verb processes a string with imbedded blocks of code. The code
Line 1,197 ⟶ 2,343:
@SAY (@INTERPOLATE "Mary had a { v } lamb");
 
// output: Mary had a litle lamb</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">
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>
</lang>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var s = "little"
var t = "Mary had a %(s) lamb"
System.print(t)</syntaxhighlight>
 
{{out}}
<pre>
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}}==
<langsyntaxhighlight lang="zkl">"Mary had a X lamb.".replace("X","big")</langsyntaxhighlight>
Generates a new string. For more info, refer to manual in the downloads section of [http://zenkinetic.com/ zenkinetic.com zkl page]
 
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly|I think the NEOGEO BIOS has a way to do this using MESSOUT but I don't understand how it works.}}
{{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}}
{{omit from|Axe}}
7,806

edits