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.
Making strings
Section titled “Making strings”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 MojoShe 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.
Special characters and long text
Section titled “Special characters and long text”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 oneLine twoName: AdaA "quoted" word and a back\slashC:\new\folder\nis a new line,\tis a tab,\"is a double quote,\\is one backslash.- An
rbefore 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.Joining strings
Section titled “Joining strings”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: 36Without 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).
Why len() doesn’t work on a string
Section titled “Why len() doesn’t work on a string”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 48 2 1café 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.
Getting one character: no plain s[0]
Section titled “Getting one character: no plain s[0]”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 knowiis at the start of a character.s[codepoint=i]ands[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].
Slicing a string
Section titled “Slicing a string”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:
HelloWorldZürZü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ü.
StringSpan: a view, not a copy
Section titled “StringSpan: a view, not a copy”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:
HelloHello!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.
Comparing strings and searching
Section titled “Comparing strings and searching”==, !=, < 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 TrueTrueTrueMOJO 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.
Coming from Python?
Section titled “Coming from Python?”| 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) |
Practice
Section titled “Practice”1. Build a greeting
Section titled “1. Build a greeting”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.
2. Count it three ways
Section titled “2. Count it three ways”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:
655ï takes 2 bytes in UTF-8, so the byte length is one more than the character count.
3. First and last name
Section titled “3. First and last name”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:
AdaLovelaceThe 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.
Stringholds UTF-8 text. Use"..."or'...',"""..."""for several lines andr"..."for raw text.- Join with
+, append with+=, repeat with*. Convert numbers withString(x)first. len(s)doesn’t compile: pickbyte_length(),count_codepoints()orcount_graphemes().s[0]doesn’t compile either: uses[byte=i],s[codepoint=i]ors[grapheme=i]. No negative indexes.- Slices look like
s[byte=a:b]ors[codepoint=a:b], and a byte index inside a character crashes. - Indexing and slicing give a read-only
StringSpanview (older name:StringSlice). UseString(view)for your own copy.
Next up: booleans, True, False and the words that combine them.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo manual: Strings: the strings section covers UTF-8, emoji, raw strings and literals.
StringAPI docs: every method onString, including indexing withbyte=,codepoint=andgrapheme=.StringSpanAPI docs: the read-only string view you get from slices.- Types and literals cheat sheet: string literal forms, escapes and the three ways to measure length.
- Unicode text segmentation (UAX #29): the official rules for what counts as one grapheme, if you want the full story.