Mojo Strings in Depth
You met String in Mojo Strings. This lesson is the toolbox: splitting a line into parts, joining parts back together, searching, replacing, trimming and slicing. Most of these methods have the same names as in Python. The part that’s really different is how Mojo thinks about “characters”, so we’ll start there, because it explains why len(s) and s[0] don’t work the way you might expect.
Bytes, code points and graphemes
Section titled “Bytes, code points and graphemes”Mojo strings are stored as UTF-8, a way of turning text into bytes. Plain English letters take 1 byte each, but é takes 2, and an emoji takes 4 or more. So “how long is this string?” has three honest answers:
- Bytes: how much space the text takes in memory.
- Code points: the Unicode values in the text. This is what Python’s
len()counts. - Graphemes: what a person would call a character. One emoji with a skin tone is one grapheme, even though it’s made of two code points.
Mojo makes you say which one you mean:
def show(s: String): print(s, "bytes:", s.byte_length(), "code points:", s.count_codepoints(), "graphemes:", s.count_graphemes())
def main(): show("cat") show("café") show("👋🏽")Output:
cat bytes: 3 code points: 3 graphemes: 3café bytes: 5 code points: 4 graphemes: 4👋🏽 bytes: 8 code points: 2 graphemes: 1For "cat", all three agree. For "café", the é takes 2 bytes. The waving hand with a skin tone is 8 bytes and 2 code points, but you see one character. That’s why len(s) is a compile error in Mojo, with a message that lists your three options:
def main(): var name = "café" print(len(name))strings-in-depth.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(name)) ^~~mojo: error: failed to parse the provided Mojo source moduleIndexing and slicing
Section titled “Indexing and slicing”s[0] doesn’t work either, for the same reason. Instead you say what kind of position you mean:
def main(): var s = "café latte" print(s[byte=0]) print(s[byte=0:3]) print(s[codepoint=3]) print(s[codepoint=0:4]) print(s[grapheme=3])Output:
ccafécaféés[byte=i]ands[byte=a:b]use byte positions. They’re the cheapest, because Mojo can jump straight to a byte, and they’re whatfind()gives you.s[codepoint=i]ands[codepoint=a:b]count code points.s[grapheme=i]counts user-visible characters.
Like lists, strings don’t accept negative positions. And a byte position must land at the start of a character. "café"[byte=4] is the second byte of é, so the program stops with “String span index, 4 does not lie on a codepoint boundary”.
Here’s why graphemes matter. An accented letter can also be written as a plain e followed by a separate “combining accent” code point:
def main(): var word = "ét́" print(word) print(word.count_codepoints(), word.count_graphemes()) print(word[grapheme=0]) print(word[codepoint=0])Output:
ét́4 2éeThe string looks like 2 characters, and the grapheme count agrees. Taking code point 0 gives you just the e, without its accent. If you cut text for display, use graphemes so you don’t split a character in half.
Looping over a string
Section titled “Looping over a string”A for loop over a String gives you one grapheme at a time. You can also loop over code points or raw bytes when you need them:
def main(): var s = "hé!" for ch in s: print(ch, end="|") print() for cp in s.codepoints(): print(cp, end="|") print() for b in s.as_bytes(): print(b, end=" ") print()Output:
h|é|!|h|é|!|104 195 169 33as_bytes() gives you a Span of UInt8 values: the actual UTF-8 bytes. You can see é take two of them, 195 and 169. To go between a single character and its number, use ord() and chr(), like in Python: ord("A") is 65, and chr(97) is "a".
Searching
Section titled “Searching”def main(): var s = "the cat sat on the mat" print("cat" in s) print(s.find("at")) print(s.rfind("at")) print(s.find("dog")) print(s.count("the")) print(s.startswith("the"), s.endswith("mat"))Output:
True520-12True Trueinsays whether the text appears at all.find(sub)gives the byte position of the first match, or-1if there’s none.rfindsearches from the end.find(sub, start)starts looking at bytestart.count(sub)counts matches that don’t overlap.startswithandendswithcheck the ends.
Watch out: find returns a byte position, not a character count. In "café latte", find("latte") returns 6, because é takes 2 bytes. That’s no problem if you use it with s[byte=...], which is exactly what it’s meant for:
def main(): var s = "café latte" var pos = s.find("latte") print(pos) print(s[byte=pos:])Output:
6latteReplacing and changing case
Section titled “Replacing and changing case”Strings have methods that give you a new string and leave the original alone:
def main(): var s = "Hello, World" print(s.replace("World", "Mojo")) print(s.upper()) print(s.lower()) print(s)Output:
Hello, MojoHELLO, WORLDhello, worldHello, Worldreplace(old, new) swaps every match. s itself is unchanged; save the result in a variable if you want to keep it.
Trimming
Section titled “Trimming”strip() removes whitespace (spaces, tabs, newlines) from both ends. lstrip() and rstrip() do one end. Give them a string of characters to remove something other than whitespace:
def main(): var line = " Ada Lovelace \n" print("[" + line.strip() + "]") print("[" + line.lstrip() + "]") print("--==title==--".strip("-=")) var file = "report.txt" print(file.removesuffix(".txt")) var greeting = "Mr. Bo" print(greeting.removeprefix("Mr. "))Output:
[Ada Lovelace][Ada Lovelace]titlereportBostrip("-=") removes any mix of - and = from both ends. removeprefix and removesuffix remove one exact piece of text, only if it’s there.
Splitting and joining
Section titled “Splitting and joining”split(sep) cuts a string at every sep and gives you a list of the parts. With no argument, it splits on runs of whitespace and drops the empty bits:
def main(): var csv = "apple,banana,,cherry" print(csv.split(",")) print(" lots of space ".split()) print("key=value=more".split("=", 1))
var lines = "one\ntwo\nthree" print(lines.splitlines())
var words: List[String] = ["red", "green", "blue"] print(", ".join(words))Output:
[apple, banana, , cherry][lots, of, space][key, value=more][one, two, three]red, green, blueThe empty item in the first line is the empty text between ,,. The 1 in split("=", 1) means “split at most once”. join goes the other way: ", ".join(words) puts ", " between the items. In Python you’d write ", ".join(words) too.
Split parts are views
Section titled “Split parts are views”The parts that split() (and strip()) give you are StringSpan values: views into the original string, not copies. That makes splitting cheap. Most of the time you can use the parts directly:
def main() raises: var line = "3,14,15" var total = 0 for part in line.split(","): total += Int(part) print(total)Output:
32Int(part) converts each piece to a number. It raises if a piece isn’t a number, which is why main is marked raises.
Because the parts are views, they stop being valid when the original string changes. Mojo catches that:
def main(): var text = String("a,b") var parts = text.split(",") text += ",c" print(parts)strings-in-depth.mojo:5:10: error: use of invalidated interior reference 'text["bytes"]' print(parts) ^strings-in-depth.mojo:4:10: note: origin was invalidated here text += ",c" ^mojo: error: failed to run the pass managerWhen you need to keep the parts, turn each one into a String:
def main(): var text = String("a,b") var kept = List[String]() for part in text.split(","): kept.append(String(part)) text += ",c" print(kept, text)Output:
[a, b] a,b,cString(part) makes a copy that owns its own text. This is the same idea as copying a Span into a List in Mojo Span.
Building strings
Section titled “Building strings”To build a string piece by piece, add to it with +=. To glue different kinds of values together, pass them all to String(...):
def main(): var report = String() for i in range(1, 4): report += "line " + String(i) + "\n" print(report, end="")
var summary = String("Total: ", 3, " lines") print(summary) print("=" * 12)Output:
line 1line 2line 3Total: 3 lines============"line " + i wouldn’t compile, because + only joins strings; that’s why the number goes through String(i) first. String("Total: ", 3, " lines") takes any number of printable values and joins them. * repeats a string. For lining up columns, Mojo has ascii_ljust(), ascii_rjust() and ascii_center(), which pad ASCII text to a width: "cat".ascii_rjust(6, ".") is "...cat".
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Length | len(s) (code points) |
s.byte_length(), s.count_codepoints() or s.count_graphemes() |
| First character | s[0] |
s[byte=0], s[codepoint=0] or s[grapheme=0] |
| Slice | s[2:5] |
s[byte=2:5] or s[codepoint=2:5] |
s.find(x) |
Code point position | Byte position, -1 if missing |
s.split(",") |
List of new strings | List of views (StringSpan) |
| Pad | s.rjust(6) |
s.ascii_rjust(6) |
"n=" + 5 |
TypeError |
Compile error: use String(5) |
The String API docs list every method, including a few not covered here, like is_ascii_digit() and codepoint_slices().
Practice
Section titled “Practice”1. Settings line
Section titled “1. Settings line”Turn the line "name=Ada; lang=Mojo; level=3" into a Dict[String, String] and print it.
Hint: split on ";", strip() each part, then split each part on "=". Wrap the pieces in String(...) before putting them in the dictionary.
Show solution
def main(): var line = "name=Ada; lang=Mojo; level=3" var settings = Dict[String, String]() for part in line.split(";"): var pair = part.strip().split("=") settings[String(pair[0])] = String(pair[1]) print(settings)Output:
{name: Ada, lang: Mojo, level: 3}Each part is a view into line, so the dictionary gets its own copies with String(...). That way it doesn’t depend on line at all.
2. Title case
Section titled “2. Title case”Write a program that turns "the quick brown fox" into "The Quick Brown Fox".
Hint: split on whitespace. For each word, take word[byte=0:1].upper() plus word[byte=1:]. Collect the words in a List[String] and " ".join them.
Show solution
def main(): var text = "the quick brown fox" var words = List[String]() for word in text.split(): words.append(String(word[byte=0:1]).upper() + String(word[byte=1:])) print(" ".join(words))Output:
The Quick Brown FoxByte slicing is fine here because the text is plain ASCII. For text that could start with é or an emoji, you’d slice by grapheme instead.
3. Fix the program
Section titled “3. Fix the program”This program should print the first character and the length of the name. It doesn’t compile. Fix it so it prints Z and 4.
def main(): var name = "Zoë!" print(name[0]) print(len(name))Hint: say which kind of position and which kind of length you mean. ë is 2 bytes, so the byte length isn’t 4.
Show solution
def main(): var name = "Zoë!" print(name[grapheme=0]) print(name.count_graphemes())Output:
Z4name.byte_length() would print 5, because ë takes two bytes. Counting graphemes gives the 4 characters a person sees.
- Strings are UTF-8. Length comes in three kinds:
byte_length(),count_codepoints()andcount_graphemes().len(s)ands[0]are compile errors. - Index and slice with
s[byte=...],s[codepoint=...]ors[grapheme=...]. No negative positions. - Search with
in,find,rfind,count,startswith,endswith.findreturns a byte position, or-1. replace,upper,lowerreturn new strings.strip(with optional characters),removeprefixandremovesuffixtrim.splitgives a list of views; useString(part)to keep a part after the original changes.sep.join(list)puts them back together.- Build strings with
+=,String(a, b, c)and*.
Next up: structs, making your own types with named fields.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- String API docs: every
Stringmethod, with examples. - StringSpan API docs: the view type that
split()andstrip()return. - Mojo manual: Types: the strings section, with emoji and grapheme examples.
- Unicode text segmentation (UAX #29): the official rules for what counts as a grapheme.