Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

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:

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

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

Code Block
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:

Code Block
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:

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

Interpolation doesn't kick in inside single quoted strings:

Code Block
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.

Code Block
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:

Code Block
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:

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

See Also

Here are some related resources on .NET string formatting: