Skip to content

String Interpolation

Nathaniel Sabanski edited this page Jan 20, 2016 · 9 revisions

Added by Rodrigo B. de Oliveira

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

The parentheses are unnecessary if the expression is just a variable:

now = "IMPORTANT"
print("Tomorrow will be $now")

String interpolation kicks in for both double and triple quoted stringstriple 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 escape the $ character to prevent interpolation:

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

You don't need to escape the $ char when it is followed by a space:

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:
System.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

See Also

Here are some related resources on .NET string formatting:

Clone this wiki locally