String interpolation (included): Difference between revisions

m
syntax highlighting fixup automation
(String interpolation (included) in Asymptote)
m (syntax highlighting fixup automation)
Line 25:
 
=={{header|11l}}==
<langsyntaxhighlight 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.’)</langsyntaxhighlight>
 
{{out}}
Line 39:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<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>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
CHAR ARRAY extra="little"
 
PrintF("Mary had a %S lamb.%E",extra)
RETURN</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Fixed, Ada.Text_IO;
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;</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 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 352:
# or: use simply use STRING concatenation #
print(("Mary had a "+extra+" lamb.", new line))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 361:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program insertString.s */
Line 615:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 627:
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">
s ← 'Mary had a ∆ lamb' ⋄ s[s⍳'∆'] ← ⊂'little' ⋄ s ← ∊s
s
Line 647:
'Mary had a ∆ lamb, its fleece was ∆ as ∆.' sInterp 'little' 'large' 42
Mary had a little lamb, its fleece was large as 42.
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">sizeOfLamb: "little"
 
print ~"Mary had a |sizeOfLamb| lamb."</langsyntaxhighlight>
 
{{out}}
Line 659:
 
=={{header|Asymptote}}==
<langsyntaxhighlight Asymptotelang="asymptote">string s1 = "big";
write("Mary had a " + s1 + " lamb");
s1 = "little";
write("Mary also had a ", s1, "lamb");</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Using the = operator
LIT = little
string = Mary had a %LIT% lamb.
Line 673:
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 679:
=={{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|BASIC256}}===
<langsyntaxhighlight lang="basic256">x$ = "big"
print "Mary had a "; x$; " lamb"
 
x$ = "little"
print "Mary also had a "; ljust(x$, length(x$)); " lamb"</langsyntaxhighlight>
 
==={{header|QBasic}}===
<langsyntaxhighlight QBasiclang="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</langsyntaxhighlight>
 
==={{header|True BASIC}}===
<langsyntaxhighlight lang="qbasic">LET x$ = "big"
PRINT "Mary had a "; x$; " lamb"
 
Line 711:
LET outstring$ = USING$("$#####", x$)
PRINT "Mary also had a "; outstring$; " lamb"
END</langsyntaxhighlight>
 
==={{header|Yabasic}}===
<langsyntaxhighlight lang="yabasic">x$ = "big"
print "Mary had a ", x$, " lamb"</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
call :interpolate %1 %2 res
Line 728:
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}}==
Line 740:
Here, the symbol for Nothing(`·`) is used as a replacement character.
 
<langsyntaxhighlight 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 ·"</langsyntaxhighlight>
 
=={{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 758:
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.
 
<langsyntaxhighlight lang="csharp">class Program
{
static void Main()
Line 771:
System.Console.WriteLine(formatted);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <iostream>
 
Line 784:
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}</langsyntaxhighlight> =={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">// Variable argument template
 
#include <string>
Line 829:
 
return out;
}</langsyntaxhighlight>
 
=={{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 848:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|Coco}}==
Line 854:
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 868:
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 889:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program Project1;
 
uses
Line 924:
writeln(Output);
 
end.</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb.
Line 932:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">PrintLn(Format('Mary had a %s lamb.', ['little']))</langsyntaxhighlight>
{{out}}
<pre>Mary had a little lamb.</pre>
Line 940:
Dyalect has a built-in [https://github.com/vorov2/dyalect/wiki/String#interpolation string interpolation] feature.
 
<langsyntaxhighlight Dyalectlang="dyalect">let lamb_size = "little"
print("Mary had a \(lamb_size) lamb.")</langsyntaxhighlight>
 
=={{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 952:
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 959:
=={{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 965:
(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 4.x :
<langsyntaxhighlight lang="elena">import extensions;
public program()
Line 981:
var s := "little";
console.printLineFormatted("Mary had a {0} lamb.",s).readChar()
}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight 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))</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 1,006:
 
=={{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 1,016:
=={{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 1,026:
"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''
<langsyntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,047:
// line 1: use of the = operator
// line 2: use of the @ and $ operator
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,058:
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]
Line 1,069:
=={{header|Forth}}==
 
<langsyntaxhighlight Forthlang="forth">variable 'src
variable #src
variable 'out
Line 1,095:
here 'out ! ," BIG" here 'out @ - #out !
format
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,104:
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">program interpolate
 
write (*,*) trim(inter("Mary had a X lamb.","X","little"))
Line 1,122:
end function inter
end program interpolate</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 1,129:
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 1,137:
x = "little"
printf("Mary also had a %s lamb", x)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,146:
 
=={{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|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 1,168:
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 1,174:
<main> //Mary @<what>
</syntaxhighlight>
</lang>
{{out|Output}}
<pre>
Line 1,182:
=={{header|Go}}==
Doc: [http://golang.org/pkg/fmt/ http://golang.org/pkg/fmt/]
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 1,195:
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 1,205:
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#}}
<langsyntaxhighlight lang="haxe">class Program {
static function main() {
var extra = 'little';
Line 1,217:
Sys.println(formatted);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,226:
=={{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 1,243:
=={{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 1,251:
Mary had a little lamb.
'Mary had a %s lamb.' rplc '%s';'little'
Mary had a little lamb.</langsyntaxhighlight>
 
Documentation:
Line 1,257:
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 1,264:
 
=={{header|Java}}==
<langsyntaxhighlight 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,272:
//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 1,311:
// it must be treated as an expression
println("Mary had a ${s}r lamb") // not $sr
}</langsyntaxhighlight>
 
{{out}}
Line 1,321:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def original Mary had a X lamb}
-> original
Line 1,328:
{S.replace X by {Y} in {original}}
-> Mary had a little lamb
</syntaxhighlight>
</lang>
 
=={{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>
Line 1,338:
=={{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 1,349:
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:
<langsyntaxhighlight lang="lua">str1 = string.format( "Mary had a %s lamb.", "little" )
str2 = ( "Mary had a %s lamb." ):format( "little" )
print( str1, str2 )</langsyntaxhighlight>
 
=== Literal characters ===
Line 1,362:
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|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
module checkit {
size$="little"
Line 1,379:
}
checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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}}==
<langsyntaxhighlight lang="actionscript">/**
<doc><h2>String interpolation, in Neko</h2>
<p><a href="https://nekovm.org/doc/view/string/">NekoVM String Library</a></p>
Line 1,398:
var sprintf = $loader.loadprim("std@sprintf", 2)
 
$print(sprintf("Mary had a %s lamb\n", "little"))</langsyntaxhighlight>
 
{{out}}
Line 1,407:
=={{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 1,420:
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 1,459:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 5ex; overflow:scroll;">
Line 1,469:
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.
<langsyntaxhighlight lang="nim">import strutils
 
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.</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight 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]:
 
<langsyntaxhighlight lang="ocaml">
let extra = "little" in
[%string "Mary had a $extra lamb."]
</syntaxhighlight>
</lang>
 
=={{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|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,546:
 
=={{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}}==
<langsyntaxhighlight Picatlang="picat">main =>
V = "little",
printf("Mary had a %w lamb\n", V),
Line 1,559:
% As a function
S = to_fstring("Mary had a %w lamb", V),
println(S).</langsyntaxhighlight>
 
 
=={{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 1,598:
Return(res);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,606:
=={{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 1,653:
Mary:
Data.s "Mary had a X lamb."
EndDataSection</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,659:
 
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|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
DefStr S
 
Line 1,717:
Print String1, "by LEFT$ and RIGHT$"
 
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 1,723:
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" perl6line>my $extra = "little";
say "Mary had a $extra lamb"; # variable interpolation
say "Mary had a { $extra } lamb"; # expression interpolation
Line 1,737:
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</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">str: "Mary had a <%size%> lamb"
size: "little"
build-markup str
Line 1,746:
;REBOL3 also has the REWORD function
str: "Mary had a $size lamb"
reword str [size "little"]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,753:
<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 1,779:
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 1,797:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aString =substr("Mary had a X lamb.", "X", "little")
see aString + nl
</syntaxhighlight>
</lang>
 
=={{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 1,816:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">"a$ = Mary had a X lamb."
a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X")
print a$
</syntaxhighlight>
</lang>
 
=={{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 1,829:
// 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,882:
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,902:
replaced := replace(original, "X", little);
writeln(replaced);
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,911:
=={{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).
<langsyntaxhighlight lang="sensetalk">put "little" into x
 
put "Mary had a [[x]] lamb." -- this is a literal string
Line 1,918:
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>
</lang>
{{out}}
<pre>
Line 1,934:
 
=={{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]
Line 1,944:
=={{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,954:
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
<langsyntaxhighlight lang="tailspin">
def size: 'little';
'Mary had a $size; lamb' -> !OUT::write
</syntaxhighlight>
</lang>
 
=={{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,976:
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,992:
set middle upper
set fun3 {aNd]}
puts [subst "$grandpa $fun1$[subst $$fun2] $fun3 $grandma"]</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 2,007:
PRINT sentence_old
PRINT sentence_new
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,018:
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 2,028:
 
==={{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 2,037:
=={{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}}
Line 2,058:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">void main() {
string size = "little";
print(@"Mary had a $size lamb\n");
stdout.printf("Mary had a %s lamb\n", size);
}</langsyntaxhighlight>
 
{{out}}
Line 2,102:
 
=={{header|Verbexx}}==
<langsyntaxhighlight lang="verbexx">////////////////////////////////////////////////////////////////////////////////////////
//
// The @INTERPOLATE verb processes a string with imbedded blocks of code. The code
Line 2,116:
@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}}==
<langsyntaxhighlight lang="javascript">var s = "little"
var t = "Mary had a %(s) lamb"
System.print(t)</langsyntaxhighlight>
 
{{out}}
Line 2,138:
 
=={{header|Vlang}}==
<langsyntaxhighlight lang="vlang">
txt := "little"
str := "Mary had a $txt lamb"
println(str)
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">char X;
[X:= "little";
Text(0, "Mary had a "); Text(0, X); Text(0, " lamb.");
]</langsyntaxhighlight>
 
=={{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]
 
10,333

edits