Mojo String Formatting
Printing values with commas gets you far, but soon you’ll want more control: a value in the middle of a sentence, a price with two decimals, a neat column of numbers. That’s string formatting. Mojo gives you t-strings for most of it, plus format(), + and a few string methods for the rest.
If you know Python’s f-strings, a lot of this will feel familiar. The big differences are the t prefix and that Python’s format specs like {x:.2f} don’t exist yet. We’ll go through what to do instead.
T-strings: values inside text
Section titled “T-strings: values inside text”Put a t in front of the quotes and write any variable in {curly braces}. Mojo puts the value there:
def main(): var name = "Ann" var age = 36 print(t"{name} is {age} years old.")Output:
Ann is 36 years old.You don’t need to convert age to text first; the t-string does that for you. Any value that print can print works inside the braces.
Any expression inside the braces
Section titled “Any expression inside the braces”The braces can hold more than a variable name. Math, method calls, function calls and even an if/else expression all work:
def main(): var name = "Ann" var age = 36 var scores: List[Int] = [90, 75] print(t"In 10 years: {age + 10}") print(t"Shouting: {name.upper()}") print(t"{len(scores)} scores: {scores}") print(t"{name} is {"an adult" if age >= 18 else "a child"}")Output:
In 10 years: 46Shouting: ANN2 scores: [90, 75]Ann is an adultThe expressions are worked out when that line runs. The literals reference has the exact rules for t-strings, including raw t-strings (rt"...").
Printing curly braces
Section titled “Printing curly braces”Since { starts an expression, how do you print a real brace? Write it twice: {{ prints { and }} prints }:
def main(): var key = "color" print(t"JSON looks like {{\"{key}\": \"blue\"}}") print(t"Use {{name}} for a placeholder")Output:
JSON looks like {"color": "blue"}Use {name} for a placeholderTurning a t-string into a String
Section titled “Turning a t-string into a String”A t-string isn’t a String yet. It’s a template that remembers its values, and it becomes text when it’s printed. That’s why print(t"...") just works. But if you want to keep the text in a variable, wrap it in String(...):
def main(): var name = "Ann" var age = 36 var label = String(t"{name} ({age})") print(label) print(label.upper())Output:
Ann (36)ANN (36)If you forget, Mojo tells you:
def main(): var age = 36 var label: String = t"Age: {age}" print(label)hello.mojo:3:25: error: cannot implicitly convert 'TString[origin_of(age), origin_of(__call_result_tmp__)]' value to 'String' var label: String = t"Age: {age}" ^~~~~~~~~~~~~mojo: error: failed to parse the provided Mojo source moduleThe fix is var label = String(t"Age: {age}"). The same goes for joining with +: "Hi " + t"{name}" doesn’t work, but "Hi " + String(t"{name}") does.
Multi-line t-strings
Section titled “Multi-line t-strings”Triple quotes work with t-strings too. Line breaks inside are kept:
def main(): var name = "Ann" var city = "Oslo" var card = String(t"""Name: {name}City: {city}""") print(card)Output:
Name: AnnCity: OsloRounding numbers (no format specs yet)
Section titled “Rounding numbers (no format specs yet)”In Python you’d write f"{price:.2f}" to show two decimals. Mojo doesn’t support format specs in t-strings:
def main(): var price = 3.14159 print(t"Price: {price:.2f}")hello.mojo:3:26: error: format specifiers are not supported in t-strings; format the value manually before interpolating print(t"Price: {price:.2f}") ^mojo: error: failed to parse the provided Mojo source moduleInstead, round the number yourself with round(x, digits):
def main(): var price = 3.14159 var total = 7.0 / 3.0 print(t"Price: {round(price, 2)}") print(t"Total: {round(total, 1)}") print(t"Even: {round(2.5, 2)}")Output:
Price: 3.14Total: 2.3Even: 2.5Two things to know about round:
- It doesn’t add zeros.
round(2.5, 2)is2.5, not2.50. If you need exactly two decimals (for money, say), you have to add the missing zero yourself, or store cents as anInt. round(x)with no digits still gives a float.round(3.7)is4.0in Mojo, while Python gives the integer4. UseInt(x)if you want to cut off the decimals and get anInt.
format(): placeholders like Python’s str.format
Section titled “format(): placeholders like Python’s str.format”Strings also have a format() method. Each {} is filled with the next value, and {0}, {1} pick a value by position:
def main(): print("{} + {} = {}".format(2, 3, 5)) print("{0} and {1}, then {0} again".format("Ann", "Bo")) print("{!r} has quotes".format("Ann"))Output:
2 + 3 = 5Ann and Bo, then Ann again'Ann' has quotes{!r} shows the value the way repr() does, with quotes around strings. What’s not supported yet: named fields like {name}, and specs like {:>8} or {:.2f}. The format module docs list exactly what works.
Most of the time, a t-string is simpler and easier to read than format(). Use format() when the template itself is stored in a variable.
Building strings with + and String(x)
Section titled “Building strings with + and String(x)”You can glue strings together with +. But + only joins strings with strings. A number has to become a string first, with String(...):
def main(): var age = 36 var line = "Age: " + String(age) line += " years" print(line) print("Pi is about " + String(3.14)) print(String("Items: ", 3, ", done: ", True))Output:
Age: 36 yearsPi is about 3.14Items: 3, done: TrueString(...) with several values glues them all together, with no spaces, which is a quick way to build a string from mixed types. "Age: " + age without String is a compile error (no matching method in call to '__add__'). This is the same as Python, where you’d need str(age).
Repeating, joining and changing case
Section titled “Repeating, joining and changing case”A few string tools you’ll use all the time:
def main(): print("=" * 20) var words: List[String] = ["red", "green", "blue"] print(", ".join(words)) var nums: List[Int] = [1, 2, 3] print(" + ".join(nums)) print("Hello".upper(), "Hello".lower())Output:
====================red, green, blue1 + 2 + 3HELLO hello*repeats a string, which is handy for lines and spacing.sep.join(list)putssepbetween the items. It works on a list of numbers too, not just strings..upper()and.lower()change the case.
Lining up columns
Section titled “Lining up columns”Python has ljust, rjust and center for padding text to a width. Mojo’s String doesn’t have those exact names:
def main(): var name = "Tea" print(name.ljust(10))hello.mojo:3:15: error: 'String' value has no attribute 'ljust' print(name.ljust(10)) ~~~~^mojo: error: failed to parse the provided Mojo source moduleInstead, it has ascii_ljust, ascii_rjust and ascii_center. They work the same way, with an optional fill character:
def main(): var items: List[String] = ["Coffee", "Tea", "Croissant"] var prices: List[Float64] = [2.5, 2.0, 3.25] for i in range(len(items)): print(items[i].ascii_ljust(10) + String(prices[i]).ascii_rjust(6)) print("-" * 16) print("Menu".ascii_center(16, "*")) print(String(7).ascii_rjust(3, "0"))Output:
Coffee 2.5Tea 2.0Croissant 3.25----------------******Menu******007ascii_ljust puts the spaces after the text (left-aligned), ascii_rjust puts them before (right-aligned, which is what you want for numbers), and ascii_center splits them on both sides. The last line pads with "0" instead of spaces.
For text that may contain accents or other non-English letters, write two tiny helpers that count code points instead:
def pad_right(text: String, width: Int) -> String: var n = width - len(text.codepoints()) if n <= 0: return text return text + " " * n
def pad_left(text: String, width: Int) -> String: var n = width - len(text.codepoints()) if n <= 0: return text return " " * n + text
def main(): print(pad_right("Café", 10) + pad_left("1.5", 6)) print(pad_right("Tea", 10) + pad_left("2.0", 6))Output:
Café 1.5Tea 2.0Now both lines line up, because len(text.codepoints()) counts é as one.
The len() gotcha
Section titled “The len() gotcha”You might expect len(text) in those helpers. In Mojo, that’s a compile error:
def main(): var word = "café" print(len(word))hello.mojo:3:11: error: `len(String/StringSlice)` is not supported because Mojo strings are UTF-8 encoded, so a single length is ambiguous: it could mean the number of UTF-8 bytes, the number of Unicode code points, or the number of user-visible characters (grapheme clusters). Use `s.byte_length()` or `len(s.bytes())` for the number of UTF-8 bytes, `len(s.codepoints())` for Unicode code points, or `len(s.graphemes())` for grapheme clusters. print(len(word)) ^~~mojo: error: failed to parse the provided Mojo source moduleThe message explains it well: “length” can mean three different things for text. Here’s what each gives for "café":
def main(): var word = "café" print(word.byte_length()) print(len(word.codepoints())) print(len(word.graphemes()))Output:
544The é takes 2 bytes in UTF-8, so the byte length is 5, but you see 4 characters. For lining up text, count characters (codepoints() or graphemes()), not bytes. Mojo Strings explains the difference in more detail.
Making your own types printable
Section titled “Making your own types printable”print, t-strings, String(...) and format() all work with any type that conforms to the Writable trait. The built-in types already do. A struct you write yourself doesn’t, until you add a small write_to method. That’s the topic of Mojo Printing Your Types, and once you’ve done it, your type works in t-strings like any other value.
Practice
Section titled “Practice”1. A price tag
Section titled “1. A price tag”Given var item = "Notebook", var price = 4.999 and var qty = 3, print exactly:
3 x Notebook = 15.0Hint: multiply first, then round(..., 2). A t-string can hold the whole line.
Show solution
def main(): var item = "Notebook" var price = 4.999 var qty = 3 print(t"{qty} x {item} = {round(price * Float64(qty), 2)}")Output:
3 x Notebook = 15.0price * Float64(qty) is 14.997, and rounding to 2 digits gives 15.0. Notice that round doesn’t add zeros, so it’s 15.0, not 15.00. Float64(qty) turns the Int into a float so the two can be multiplied.
2. A small table
Section titled “2. A small table”Print this table, with the names padded to 8 characters and the scores right-aligned in 4:
Ann 91Bo 7Charlie 100Hint: use ascii_ljust for the names and ascii_rjust for the scores, with String(score) to turn each score into text.
Show solution
def main(): var names: List[String] = ["Ann", "Bo", "Charlie"] var scores: List[Int] = [91, 7, 100] for i in range(len(names)): print(names[i].ascii_ljust(8) + String(scores[i]).ascii_rjust(4))Output:
Ann 91Bo 7Charlie 100Each name is padded to 8 characters, and each score is padded on the left to 4, so the last digits line up.
3. Initials
Section titled “3. Initials”Given the list ["ada", "grace", "linus"], print ADA / GRACE / LINUS.
Hint: join first, then .upper() on the result.
Show solution
def main(): var names: List[String] = ["ada", "grace", "linus"] print(" / ".join(names).upper())Output:
ADA / GRACE / LINUS" / ".join(names) builds ada / grace / linus, and .upper() turns the whole string into capitals.
- T-strings (
t"{name} is {age}") put any expression inside text; write{{and}}for real braces. - A t-string isn’t a
String: wrap it inString(t"...")to store it or join it with+. - Format specs like
{x:.2f}aren’t supported. Useround(x, 2), which doesn’t add trailing zeros. "{} and {}".format(a, b)works with{},{0}and{!r}, but not names or widths; on aStringvariable it can raise.- Join strings with
+, and turn other values into text withString(x). *repeats,sep.join(list)joins,.upper()/.lower()change case.- Pad columns with
ascii_ljust,ascii_rjustandascii_center(plain English text), or countlen(s.codepoints())yourself when text has accents.len()on a string doesn’t compile.
Next up: Mojo Variables, how var works, type annotations, and where a variable lives.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo literals reference: string and t-string literals, raw strings and escapes.
- format module: what
format()supports and what it doesn’t yet. - String: every method on
String, includingjoin,upperandbyte_length. - TString: the type behind t-strings.
- Writable trait: what a type needs to be printed and used in t-strings.