Skip to content

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.

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.

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: 46
Shouting: ANN
2 scores: [90, 75]
Ann is an adult

The expressions are worked out when that line runs. The literals reference has the exact rules for t-strings, including raw t-strings (rt"...").

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 placeholder

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 module

The 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.

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: Ann
City: Oslo

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 module

Instead, 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.14
Total: 2.3
Even: 2.5

Two things to know about round:

  • It doesn’t add zeros. round(2.5, 2) is 2.5, not 2.50. If you need exactly two decimals (for money, say), you have to add the missing zero yourself, or store cents as an Int.
  • round(x) with no digits still gives a float. round(3.7) is 4.0 in Mojo, while Python gives the integer 4. Use Int(x) if you want to cut off the decimals and get an Int.

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 = 5
Ann 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.

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 years
Pi is about 3.14
Items: 3, done: True

String(...) 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).

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, blue
1 + 2 + 3
HELLO hello
  • * repeats a string, which is handy for lines and spacing.
  • sep.join(list) puts sep between the items. It works on a list of numbers too, not just strings.
  • .upper() and .lower() change the case.

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 module

Instead, 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.5
Tea 2.0
Croissant 3.25
----------------
******Menu******
007

ascii_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.5
Tea 2.0

Now both lines line up, because len(text.codepoints()) counts é as one.

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 module

The 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:

5
4
4

The é 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.

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.

Given var item = "Notebook", var price = 4.999 and var qty = 3, print exactly:

3 x Notebook = 15.0

Hint: 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.0

price * 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.

Print this table, with the names padded to 8 characters and the scores right-aligned in 4:

Ann 91
Bo 7
Charlie 100

Hint: 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 91
Bo 7
Charlie 100

Each name is padded to 8 characters, and each score is padded on the left to 4, so the last digits line up.

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 in String(t"...") to store it or join it with +.
  • Format specs like {x:.2f} aren’t supported. Use round(x, 2), which doesn’t add trailing zeros.
  • "{} and {}".format(a, b) works with {}, {0} and {!r}, but not names or widths; on a String variable it can raise.
  • Join strings with +, and turn other values into text with String(x).
  • * repeats, sep.join(list) joins, .upper()/.lower() change case.
  • Pad columns with ascii_ljust, ascii_rjust and ascii_center (plain English text), or count len(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

1. How do you show price = 3.14159 with two decimals in Mojo?
2. What does print(t"Use {{name}} here") print?
3. Why does var s: String = t"Age: {age}" fail?
4. What does print("ab" * 3) print?
5. How do you count the characters in "café"?

  • 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, including join, upper and byte_length.
  • TString: the type behind t-strings.
  • Writable trait: what a type needs to be printed and used in t-strings.