Skip to content

Mojo Strings

A string is a piece of text: a name, a message, a line from a file. In Mojo, the main text type is String. A lot of it works like Python’s str, but Mojo is much more careful about what “one character” means, so a few familiar things (like len(s) and s[0]) work differently. This page shows you the basics and explains why.

Put text in double or single quotes. Both mean the same thing:

def main():
var first = "Hello"
var second = 'Mojo'
var quote = "She said 'hi'"
print(first, second)
print(quote)

Output:

Hello Mojo
She said 'hi'

Using one kind of quote on the outside lets you use the other kind inside without any fuss. There’s no separate “character” type in Mojo: 'A' is just a string with one letter in it.

A backslash starts an escape sequence, a way to write characters you can’t type directly:

def main():
print("Line one\nLine two")
print("Name:\tAda")
print("A \"quoted\" word and a back\\slash")
print(r"C:\new\folder")

Output:

Line one
Line two
Name: Ada
A "quoted" word and a back\slash
C:\new\folder
  • \n is a new line, \t is a tab, \" is a double quote, \\ is one backslash.
  • An r before the quotes makes a raw string: backslashes are kept as they are. Handy for Windows paths and patterns.

For text over several lines, use triple quotes. The line breaks become part of the string:

def main():
var poem = """Roses are red,
Mojo is fast."""
print(poem)

Output:

Roses are red,
Mojo is fast.

Use + to join strings, += to add to the end of one, and * to repeat one:

def main():
var greeting = "Hello"
greeting += ", Ada"
print(greeting + "!")
print("-" * 12)

Output:

Hello, Ada!
------------

String is mutable: += changes the string in place. Like in Python, + only joins strings with strings. Adding a number needs a conversion:

def main():
var age = 36
print("Age: " + String(age))

Output:

Age: 36

Without String(...), you get no matching method in call to '__add__'. If you only want to print, print("Age:", age) or a t-string like print(t"Age: {age}") is simpler (see the String Formatting lesson).

In Python, len("café") is 4. In Mojo, it doesn’t compile:

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

(We left out one note: line.) The message explains it well. Mojo stores text as UTF-8, the encoding used almost everywhere on the web. In UTF-8, plain English letters take 1 byte each, but é takes 2 bytes, many Asian characters take 3, and emoji take 4 or more. So “how long is this string?” has three honest answers:

Unit What it counts Method
Bytes Raw UTF-8 bytes in memory s.byte_length()
Code points Unicode “characters” in the technical sense s.count_codepoints()
Graphemes What a person would call one character s.count_graphemes()
def main():
var word = "café"
var wave = "👋🏽"
print(word.byte_length(), word.count_codepoints(), word.count_graphemes())
print(wave.byte_length(), wave.count_codepoints(), wave.count_graphemes())

Output:

5 4 4
8 2 1

café is 5 bytes (the é is 2) but 4 characters. The waving hand with a skin tone is 8 bytes and 2 code points (a hand plus a skin-tone modifier), yet a person sees one character. The Mojo types manual has more examples like flags and family emoji.

For the same reason, s[0] doesn’t compile: position 0 could mean the first byte, the first code point or the first grapheme. You have to say which one with a keyword:

def main():
var city = "Zürich"
print(city[byte=0])
print(city[codepoint=1])
print(city[grapheme=1])

Output:

Z
ü
ü
  • s[byte=i] counts in bytes. It’s fast, but it’s only safe when you know i is at the start of a character.
  • s[codepoint=i] and s[grapheme=i] count characters, so ü is position 1 either way.

When you loop over a string with for ch in city:, you also get one grapheme at a time. Loops come a few lessons later, in Mojo For.

Indexes start at 0, like in Python. Negative indexes aren’t supported: s[byte=-1] is a compile error. To get the last character of ASCII text, use s[byte=s.byte_length() - 1].

Slices work the same way, with a keyword in front of the range. As in Python, the end of the range isn’t included:

def main():
var text = "Hello, World"
print(text[byte=0:5])
print(text[byte=7:text.byte_length()])
var city = "Zürich"
print(city[codepoint=0:3])
print(city[byte=0:3])

Output:

Hello
World
Zür
Zü

city[codepoint=0:3] gives the first three characters. city[byte=0:3] gives the first three bytes, and since ü is 2 bytes, that’s only Zü.

When you index or slice a String, you don’t get a new String. You get a StringSpan: a lightweight view that points into the original string’s memory. Making one is cheap, because nothing is copied.

def main():
var text = "Hello, World"
var view = text[byte=0:5]
var owned = String(view)
owned += "!"
print(view)
print(owned)

Output:

Hello
Hello!

A span is read-only. When you need a string you can change or keep around on its own, turn it into a String with String(view). Most functions that read text (like print) accept a span directly, so you only need String(...) when you want your own copy.

==, !=, < and > compare strings, and in checks whether one string contains another:

def main():
var lang = "Mojo"
print(lang == "Mojo", lang != "Python")
print("apple" < "banana")
print("oj" in lang)
print(lang.upper(), lang.lower())

Output:

True True
True
True
MOJO mojo

< compares alphabetically, letter by letter (strictly, by code point, so all uppercase letters come before lowercase ones). String has many more methods, such as find, replace, split and strip. You’ll meet them in Mojo Strings in Depth, and the String API docs list them all.

Python Mojo
Text type str (can’t be changed) String (can be changed with +=)
Length len(s) s.byte_length(), s.count_codepoints() or s.count_graphemes()
One character s[0] s[byte=0], s[codepoint=0] or s[grapheme=0]
Last character s[-1] No negative indexes: s[byte=s.byte_length() - 1] for ASCII
Slice s[1:4] s[byte=1:4] or s[codepoint=1:4]
"Age: " + 36 TypeError Compile error; use String(36)

Create var name = "Grace", then build the string Hello, Grace! using + and print it. Then print a line of 13 = characters under it.

Hint: "=" * 13.

Show solution
def main():
var name = "Grace"
var message = "Hello, " + name + "!"
print(message)
print("=" * 13)

Output:

Hello, Grace!
=============

+ joins the pieces into one new String, and * repeats a string.

Print the byte length, code point count and grapheme count of "naïve".

Hint: ï is not an ASCII letter.

Show solution
def main():
var word = "naïve"
print(word.byte_length())
print(word.count_codepoints())
print(word.count_graphemes())

Output:

6
5
5

ï takes 2 bytes in UTF-8, so the byte length is one more than the character count.

Given var full = "Ada Lovelace", print the first name and the last name on separate lines using slices.

Hint: the space is at index 3, and all the letters are ASCII, so byte positions are fine.

Show solution
def main():
var full = "Ada Lovelace"
print(full[byte=0:3])
print(full[byte=4:full.byte_length()])

Output:

Ada
Lovelace

The first slice stops before the space; the second starts just after it and runs to the end. Later you’ll learn find and split, which find the space for you.

  • String holds UTF-8 text. Use "..." or '...', """...""" for several lines and r"..." for raw text.
  • Join with +, append with +=, repeat with *. Convert numbers with String(x) first.
  • len(s) doesn’t compile: pick byte_length(), count_codepoints() or count_graphemes().
  • s[0] doesn’t compile either: use s[byte=i], s[codepoint=i] or s[grapheme=i]. No negative indexes.
  • Slices look like s[byte=a:b] or s[codepoint=a:b], and a byte index inside a character crashes.
  • Indexing and slicing give a read-only StringSpan view (older name: StringSlice). Use String(view) for your own copy.

Next up: booleans, True, False and the words that combine them.

Quick check

1. What happens with var s = "hello" and print(len(s))?
2. What does "café".byte_length() return?
3. How do you get the first character of name by code point?
4. What do you get from text[byte=0:5]?