Skip to: Site menu | Main content

String Interpolation Print

String interpolation allows you to insert the value of almost any valid boo expression inside a string by quoting the expression with ${}.

String interpolation kicks in for both [double] and triple quoted strings:

print("Now is ${date.Now}.")
print("Tomorrow will be ${date.Now + 1d}")

print("""
----
Life, the Universe and Everything: ${len('answer to life the universe and everything')}.
----
""")

You can scape the $ character to prevent interpolation:

print("Now is \${date.Now}.") # outputs: Now is ${date.Now}.

You don't need to scape the $ char when it is not followed by the { character:

print("Calabresa R$ 4,50.")

Interpolation doesn't kick in inside [single quoted strings]:

print('Now is ${date.Now}.') # outputs: Now is ${date.Now}.

String Formatting

Boo also has the "%" (modulus) operator as shorthand for .NET/Mono's string.Format method. This is a little more similar to Python's string interpolation, too.

s = "Right now it is {0}.  Say hi to {1}."
print s % (date.Now, "Mary")

//the above is basically shorthand for .NET's string.Format method:
mystr = string.Format("x = {0}, y = {1}", x, y)

//You can also pass the same parameters to Console.Write or WriteLine
//if you just want to print out a formatted string:
Console.WriteLine("x = {0}, y = {1}", x, y)

Combine boo and .net's string formatting

This tip suggested by Arron Washington. You can combine the two above techniques to get the best of both, like in this example:

first = "Reed"
last = "H"
age = 2
print "${first} ${last} is {0:00} years old." % (age,)
//--> Reed H is 02 years old.

Another way is to pass formatting codes to the ToString method:

print age.ToString("00")
//--> 02