Tern

7. Strings

Text processing is a large part of everyday programming: reading input, splitting lines, searching, and formatting output. This chapter covers Tern's str type in depth: indexing and slicing, the built-in string functions, parsing numbers, f-strings, and the fmt module for formatting numbers. It ends with a small parser that ties them together.

Strings are values

A str is a sequence of bytes, written in double quotes. Like every value in Tern, a string behaves like a copy, and it can't be changed in place. Functions like upper and replace return a new string:

fn main():
    city = "Lisbon"
    loud = city.upper()
    print(city, loud)
    greeting = "Hello"
    greeting += ", " + city        # builds a new string (cheaply) and reassigns
    print(greeting)
Output
Lisbon LISBON
Hello, Lisbon

Assigning into a string is an error, and so is using int() to parse one:

Does not compile
fn main():
    s = "hello"
    s[0] = "H"
    n = int("42")
    print(s, n)
Compiler output
3: error: strings can't be changed in place; build a new one, e.g. `s = s[..i] + x + s[i + 1..]`
4: error: int() needs a float
4: hint: to parse a string, use `s.to_int(default)`, e.g. `"42".to_int(0)`

Building a long string with += in a loop is fine: when nothing else shares the string, Tern grows it in place.

Indexing and slicing

len(s) is the length in bytes. s[i] is the byte at index i, as a one-byte string, and s[a..b] is a substring, with the same rules as array slices:

fn main():
    s = "2024-06-15"
    print(len(s), s[0], s[5..7], s[..4], s[8..])
    year = s[..4].to_int(0)
    print(year + 1)
    for i in 0..3:
        print(i, s[i])
Output
10 2 06 2024 15
2025
0 2
1 0
2 2

For ASCII text (English letters, digits, punctuation) a byte is a character. Text in other scripts is stored as UTF-8, where one character can take several bytes, so len("héllo") is 6, and s[1] of it is only the first half of é. Strings as a whole (printing, comparing, find, split, replace) work fine with any UTF-8 text; only the positions are in bytes.

Searching and testing

fn main():
    line = "ERROR 2024-06-15 disk full on /dev/sda1"
    print(line.starts_with("ERROR"), line.ends_with("sda1"))
    print(line.contains("disk"), "memory" in line)
    at = line.find("/dev")
    print(at, line[at..])
    print(line.find("warning"))
Output
true true
true false
30 /dev/sda1
-1

s.find(sub) returns the index of the first match, or -1 when there is none. sub in s is the same test as s.contains(sub).

Changing case, trimming, replacing

fn main():
    raw = "   Hello,  World!   "
    clean = raw.trim()
    print("[" + clean + "]")
    print(clean.lower(), clean.upper())
    print(clean.replace("l", "L"), clean.replace("  ", " "))
    print("=" * 12, "ab".repeat(3))
Output
[Hello,  World!]
hello,  world! HELLO,  WORLD!
HeLLo,  WorLd! Hello, World!
============ ababab

trim removes whitespace at both ends. replace replaces every occurrence. upper and lower change ASCII letters only.

Splitting and joining

s.split(sep) cuts a string into an array of pieces; sep.join(parts) glues an array of strings together. As in Python, join is called on the separator:

fn main():
    csv = "ada,36,london"
    fields = csv.split(",")
    print(fields, len(fields))
    print(" | ".join(fields))
    print("a,,b".split(","))
    words = "the quick brown fox".split(" ")
    initials = ""
    for w in words:
        initials += w[0].upper()
    print(initials)
Output
["ada", "36", "london"] 3
ada | 36 | london
["a", "", "b"]
TQBF

Empty pieces are kept: "a,,b".split(",") has three elements.

Parsing numbers

s.to_int(default) and s.to_float(default) parse a whole string as a number. If the string is not a number, you get the default you passed, so there is no exception to handle. Pick a default that can't be a real value, or check first:

fn main():
    for text in ["42", " 7 ", "3.5", "abc"]:
        n = text.trim().to_int(-1)
        x = text.trim().to_float(-1.0)
        print(f"[{text}] int={n} float={x}")
Output
[42] int=42 float=42.0
[ 7 ] int=7 float=7.0
[3.5] int=-1 float=3.5
[abc] int=-1 float=-1.0

Going the other way, str(x) turns an int, float, or bool into text.

Bytes and characters

s.byte(i) gives the byte at i as an int, and chr(n) makes a one-byte string from a number. Together they handle simple character arithmetic, like a Caesar cipher:

fn shift(s: str, k: int) str:
    out = ""
    for ch in s:
        b = ch.byte(0)
        if b >= 97 and b <= 122:              # a to z
            out += chr((b - 97 + k) % 26 + 97)
        else:
            out += ch
    return out

fn main():
    secret = shift("attack at dawn", 3)
    print(secret, "->", shift(secret, 23))
Output
dwwdfn dw gdzq -> attack at dawn

To write a byte or a character by its number, use an escape: \xNN is one byte, and \u00e9 or \u{1F600} is a Unicode character (stored as its UTF-8 bytes, so it can take up to four):

fn main():
    sep = "\x01"                      # a byte that won't appear in normal text
    key = "2026-09-28" + sep + "checkout"
    parts = key.split(sep)
    print(len(sep), parts[1], "caf\u00e9" == "café", len("\u{1F600}"), "\u{1F600}")
Output
1 checkout true 4 😀

For binary data (an image's pixels, a file's bytes, a network buffer), use [byte]: one byte per element, numbers from 0 to 255. s.to_bytes() turns a string into one and bs.to_str() turns it back, without copying. Arithmetic on bytes gives an int, and byte(n) stores one back (keeping its low 8 bits):

fn main():
    bs = "Tern".to_bytes()
    for i in 0..len(bs):
        bs[i] = byte(bs[i] ^ 32)              # flip ASCII case
    print(bs, bs.to_str(), bs[0] + bs[1])
Output
[116, 69, 82, 78] tERN 185

The reference has the details.

f-strings and formatting

An f-string evaluates each {expression} and inserts the result. The value must be an int, float, bool, or str. {{ and }} are literal braces:

fn main():
    item = "tea"
    qty = 3
    price = 2.5
    print(f"{qty} x {item} = {float(qty) * price}")
    print(f"{item.upper()} costs {price} {{per cup}}")
Output
3 x tea = 7.5
TEA costs 2.5 {per cup}

f-strings have no format specs. For fixed decimals, padding, and digit grouping, use the standard fmt module:

Does not compile
fn main():
    price = 3.14159
    print(f"{price:.2f}")
Compiler output
3: error: can't read `price:.2f` inside the f-string
3: hint: f-strings have no format specs: `import fmt`, then `{fmt.fixed(x, 2)}` (2 decimals), `fmt.zero_pad(n, 3)`, `fmt.pad_left(s, width, " ")`
import fmt

fn main():
    rows = ["apples", "kiwis", "watermelons"]
    cents = [349, 1205, 99]
    for i, name in rows:
        print(fmt.pad_right(name, 12, ".") + fmt.pad_left(fmt.cents(cents[i]), 7, " "))
    print(fmt.fixed(3.14159, 2), fmt.zero_pad(7, 3), fmt.thousands(1234567))
Output
apples......   3.49
kiwis.......  12.05
watermelons.   0.99
3.14 007 1,234,567

import fmt makes the module's functions available as fmt.name(...). Modules are covered in chapter 12, and the fmt page lists every function.

Putting it together

A tiny parser for key = value configuration lines, skipping blanks and comments. (The loop variable raw is read-only, like all loop variables, so the trimmed line gets its own name.)

fn main():
    text = "# server config\nhost = example.com\nport = 8080\n\ndebug = true\n"
    settings: {str: str} = {}
    for raw in text.split("\n"):
        line = raw.trim()
        if line == "" or line.starts_with("#"):
            continue
        eq = line.find("=")
        if eq < 0:
            print("bad line:", line)
            continue
        settings[line[..eq].trim()] = line[eq + 1..].trim()
    print(settings)
    port = settings.get("port", "80").to_int(80)
    host = settings["host"]
    print(f"connecting to {host}:{port}")
Output
{"host": "example.com", "port": "8080", "debug": "true"}
connecting to example.com:8080

Try it

Write fn is_palindrome(s: str) bool that ignores case and spaces, so "Never odd or even" is a palindrome. Build a cleaned string with only the non-space characters, lowercased, then compare bytes from both ends toward the middle with a while loop.

Solution

fn is_palindrome(s: str) bool:
    clean = s.lower().replace(" ", "")
    i = 0
    j = len(clean) - 1
    while i < j:
        if clean[i] != clean[j]:
            return false
        i += 1
        j -= 1
    return true

fn main():
    for s in ["Never odd or even", "tern", "A man a plan a canal Panama"]:
        print(is_palindrome(s), s)
Output
true Never odd or even
false tern
true A man a plan a canal Panama

Next: 8. Enums and match. Reference: §10 Strings, §12 Printing.

Source: docs/tour/07-strings.md. Every example on this page is compiled and run by tern x test docs.