Mojo Error: len(String/StringSlice) is not supported
error: `len(String/StringSlice)` is not supported because Mojo strings are UTF-8 encoded, so a single length is ambiguous is what you get for len(s) on a string. It surprises everyone coming from Python. The message is long, but it’s one of the friendliest in Mojo: it already lists the three fixes. You only have to pick the length you mean. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def main(): var s = "hello" print(len(s))length.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(s)) ^~~<unknown>:0: note: 'len' declared heremojo: error: failed to parse the provided Mojo source moduleStringSlice in the message is the older name of StringSpan, the type you get from things like s.split(","). So the same error appears for len(part) on a piece of a split string.
What it means
Section titled “What it means”Mojo stores text as UTF-8, the same encoding most files and web pages use. In UTF-8, a plain English letter takes one byte, but é takes two, and an emoji or a flag can take four or more. So “how long is this string?” has three honest answers:
| Length | What it counts | Use it for |
|---|---|---|
| Bytes | the raw UTF-8 bytes | memory, files, network sizes |
| Code points | Unicode characters, the way Python’s len counts |
most text processing |
| Graphemes | what a person sees as one character | showing text, cursor positions, “max 20 characters” rules |
For "hello" all three are 5, which is why the error can feel pointless. For other text they differ, and Mojo makes you say which one you need instead of picking one silently.
How to fix it
Section titled “How to fix it”Fix 1: Use the length you mean
Section titled “Fix 1: Use the length you mean”Here are all three on a few strings, so you can see the difference:
def main(): var word = "café" print(word.byte_length(), len(word.codepoints()), len(word.graphemes()))
var flag = "🇯🇵" print(flag.byte_length(), len(flag.codepoints()), len(flag.graphemes()))
var plain = "hello" print(plain.byte_length(), len(plain.codepoints()), len(plain.graphemes()))Output:
5 4 48 2 15 5 5"café": 5 bytes (theétakes two), 4 code points, 4 visible characters.- The Japanese flag: 8 bytes, 2 code points (two “regional indicator” symbols), but a reader sees one flag.
"hello": plain ASCII, so all three agree.
Which to pick:
- Not sure? Use
len(s.codepoints()). It matches Python’slen(s). - Checking if a string is empty, or ASCII-only data like codes and IDs:
s.byte_length()is the fastest. - Anything about what a user sees, like a username limit:
len(s.graphemes()).
s.count_codepoints() and s.count_graphemes() give the same numbers as the len(...) versions. You’ll find all of these methods in the String reference.
Fix 2: Check for an empty string without a length
Section titled “Fix 2: Check for an empty string without a length”if len(s) == 0: is a common reason to reach for len. You don’t need a length for that, because an empty string is false:
def main(): var name = String("") if not name: print("Please enter a name")Output:
Please enter a nameif name: works the other way round, for “not empty”.
Fix 3: Loop over the string, not over range(len(s))
Section titled “Fix 3: Loop over the string, not over range(len(s))”for i in range(len(s)): ... s[i] is a Python pattern that fails twice in Mojo: once for len, and once for s[i], which gives String does not support direct positional indexing like `s[i]` . Loop over the string itself:
def main(): var word = "héllo" for c in word: print(c, end=" ") print()Output:
h é l l ofor c in word goes through the string one visible character (grapheme) at a time. for c in word.codepoints() and for b in word.bytes() exist too. If you really need a position, Mojo lets you say which kind: s[byte=i], s[codepoint=i] or s[grapheme=i]. See Mojo Strings in Depth.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Copied Python code:
len(name) > 20,if len(line) == 0,range(len(word)). - Pieces from
split:len(part)on eachStringSpanpiece. The same fixes work, for examplepart.byte_length(). - Padding and alignment, where you count characters to line up columns. For plain ASCII tables,
byte_length()and theascii_ljuststyle helpers go together. See Mojo String Formatting.
len still works on lists, dicts and other collections. It’s only strings that need you to choose.
Related errors
Section titled “Related errors”'X' value has no attribute 'Y': what you get fors.length()ors.len().- use of unknown declaration ‘x’: other Python built-ins, like
str, that don’t exist in Mojo. - All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Username check
Section titled “1. Username check”Write a function valid_username(name: String) -> Bool that returns True when the name has between 3 and 12 visible characters. Test it with "Ada", "Al" and "Zoë".
Hint: “visible characters” means graphemes.
Show solution
def valid_username(name: String) -> Bool: var n = len(name.graphemes()) return n >= 3 and n <= 12
def main(): print(valid_username("Ada")) print(valid_username("Al")) print(valid_username("Zoë"))Output:
TrueFalseTrue"Zoë" is 4 bytes, but a user sees 3 letters, so counting graphemes gives the answer a person would expect. With byte_length(), a name full of accented letters would hit the limit too early.
len(s)on a string is a compile error in Mojo, because “length” is ambiguous in UTF-8.s.byte_length()counts bytes,len(s.codepoints())counts characters like Python,len(s.graphemes())counts what users see.- Check for empty text with
if not s:, no length needed. - Loop with
for c in s:instead ofrange(len(s))ands[i]. lenstill works on lists and dicts.
Next up: does not conform to trait ‘Writable’, the error you get when you print your own struct.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Types in the Mojo manual:
Stringand how Mojo stores text. Stringin the standard library: every method, includingbyte_length,codepointsandgraphemes.- Mojo tips for Python devs: string differences from Python.
- Mojo Strings: our lesson on everyday string work.