Working with text

Strings have methods for the everyday jobs: changing case, trimming, searching, splitting and replacing. Each method gives a new string (or list); the string itself never changes.

name: str = "  Ann Lee  "
clean: str = name.trim()
print(clean)
print(clean.upper())
print(clean.lower())
print(len(clean))

Output:

Ann Lee
ANN LEE
ann lee
7
MethodGives
len(s)the number of characters, an int
s.upper(), s.lower()the text in upper or lower case
s.trim()the text without spaces, tabs and line breaks at its ends
s.contains(t)true if t is somewhere in s
s.starts(t), s.ends(t)true if s starts or ends with t
s.index(t)the position of the first t in s, or -1
s.matches(pattern)true if s matches a pattern such as "*.csv"
s.part(start, end)the characters from start up to (not including) end
s.replace(old, new)the text with every old replaced by new
s.split(sep)the parts between each sep, a [str]
s.split()the words: the parts between spaces, tabs and line breaks
s.chars()the characters, a [str]
s.csv(), s.csv(sep)the rows of CSV text, a [[str]]
s.category()the Unicode category of its first character: "Lu", "Nd", …
list.join(sep)the strings of a [str] joined with sep between them
s.lpad(width, fill), s.rpad(width, fill)the text made width characters long with fill at the start or the end (a space if not given)
s.hex(), s.base64(), s.base64url()the text’s bytes encoded; unhex(), unbase64() and unbase64url() read them back (see Encodings)
s.gzip(), s.deflate()the text’s bytes compressed; gunzip() and inflate() give them back (see Compression)

Characters, not bytes

Luma text is Unicode. len, index, part and chars count characters, so letters like õ, ä, ö, ü count as one each, as you would count them:

word: str = "tööd"
print(len(word))
print(word.index("d"))
print(word.part(1, 3))
print(word.chars())

Output:

4
3
öö
["t", "ö", "ö", "d"]

To work with the bytes themselves, convert the text to a [byte].

What kind of character

c.category() gives the Unicode general category of a text’s first character, two letters: what kind of character it is, in any script.

print("A".category())
print("ä".category())
print("7".category())
print("½".category())
print(" ".category())
print("!".category())
print("€".category())
print("😀".category())
print("中文".category())
n: int = 0
"Tere, maailm! 123".chars().walk(c) {
    if c.category().starts("L") {
        n = n + 1
    }
}
print(n)

Output:

Lu
Ll
Nd
No
Zs
Po
Sc
So
Lo
10
First letterKindThe two letters
LlettersLu upper case, Ll lower case, Lt title case, Lm modifier, Lo other (Chinese, Arabic, …)
Mmarks that go on the letter beforeMn, Mc, Me
NnumbersNd digits of any script, Nl letter-like (Ⅻ), No other (½, ²)
PpunctuationPc, Pd dashes, Ps Pe brackets, Pi Pf quotes, Po other
SsymbolsSm math, Sc currency, Sk modifier, So other (emoji)
ZseparatorsZs spaces, Zl line, Zp paragraph
CotherCc control (\n, \t), Cf format, Co private use, Cs surrogate, Cn unassigned
  • An empty text gives "". Bytes that aren’t UTF-8 count as the character U+FFFD, So, as Go reads them.
  • The categories are those of the Unicode version of Go’s unicode package (15.0), the same in luma run and in built programs.

Upper and lower case

upper and lower know the letters of every alphabet, not only a to z:

print("õun, äädikas, šokolaad".upper())
print("ΑΘΗΝΑ ЖУРНАЛ".lower())

Output:

ÕUN, ÄÄDIKAS, ŠOKOLAAD
αθηνα журнал

Each letter becomes exactly one letter, so the German ß stays ß in upper case.

Searching

line: str = "error: disk full"
print(line.starts("error"))
print(line.contains("disk"))
print(line.index("disk"))
print(line.index("cpu"))
if line.ends("full") {
    print("full!")
}

Output:

true
true
7
-1
full!

index gives -1 when the text isn’t there, so it can be checked without try.

Matching a pattern

s.matches(pattern) says whether the text fits a pattern, the ones a folder’s find uses:

names: [str] = ["report.csv", "photo.JPG", "notes.txt", "data-2024.csv"]
names.walk(n) {
    if n.matches("*.csv") {
        print(n)
    }
}
print("photo.JPG".matches("*.[jJ][pP][gG]"))
print("logs/2024/x.txt".matches("logs/**/*.txt"))

Output:

report.csv
data-2024.csv
true
true

The patterns are those of find: * is any characters (also none), ? one character, [a-z] one of a set, and two stars as a whole part are any number of folders. Upper and lower case are different, and a text that starts with . matches only a pattern that starts with ., as with file names.

Taking a part

part(start, end) gives the characters from start up to, but not including, end. Positions start at 0, and end can be len(s) for the rest of the text:

title: str = "Hello, world"
comma: int = title.index(",")
print(title.part(0, comma))
print(title.part(comma + 2, len(title)))

Output:

Hello
world

Positions outside the text raise error 2, like a list index:

"Hello".part(2, 9)     // runtime error: part(2, 9) is out of range (length 5)

Splitting and joining

csv: str = "Ann,30,Tallinn"
fields: [str] = csv.split(",")
print(fields)
print(fields.join(" | "))
words: [str] = "  many   spaces\there  ".split()
print(words)
print(words.join("-"))

Output:

["Ann", "30", "Tallinn"]
Ann | 30 | Tallinn
["many", "spaces", "here"]
many-spaces-here
  • split(sep) keeps empty parts: "a,,b".split(",") is ["a", "", "b"].
  • split() without an argument splits at any run of spaces, tabs and line breaks and drops empty parts.
  • split("") gives the characters, like chars().

CSV

text.csv() reads CSV text, the format spreadsheets export, into rows of fields, a [[str]]; rows.csv() writes rows as CSV text:

text: str = "name,city,note\nAnn,Tallinn,\"likes tea, not coffee\"\nBo,Tartu,\"said \"\"hi\"\"\"\n"
rows: [[str]] = text.csv()
print(rows[1][2])
print(rows[2][2])
print(len(rows))
rows[] = ["Cy", "Narva", "two\nlines"]
print(rows.csv())
print("a;b\n1;2".csv(";"))

Output:

likes tea, not coffee
said "hi"
3
name,city,note
Ann,Tallinn,"likes tea, not coffee"
Bo,Tartu,"said ""hi"""
Cy,Narva,"two
lines"

[["a", "b"], ["1", "2"]]
  • It reads CSV as RFC 4180 says and Python’s csv module does: a field in quotes can hold the separator, line breaks and "" (one "). Lines end in \n, \r\n or \r; empty lines are passed over; a UTF-8 BOM at the start is dropped; rows can have different numbers of fields.
  • csv(";") and csv("\t") use another separator, one character. Writing puts a field in quotes only when it has to (the separator, a quote or a line break in it), and ends every row in \n.
  • It is fast in luma run too: 200,000 rows (4.5 MB) are read in about 0.1 seconds. For columns, types and statistics, see Tables.

Replacing

print("2024-01-15".replace("-", "/"))
print("aaa".replace("a", "bb"))

Output:

2024/01/15
bbbbbb

replace replaces every match, from left to right.

Padding

lpad adds characters at the start until the text is as long as you want, and rpad adds them at the end. Without a second argument, they add spaces:

print("7".lpad(3, "0"))
print("[${"42".lpad(6)}]")
print("[${"Ann".rpad(6)}]")

Output:

007
[    42]
[Ann   ]

That gives leading zeros, and columns that line up: rpad for text on the left, lpad for numbers on the right.

names: [str] = ["Ann", "Bartholomew", "Bo"]
scores: [int] = [97, 100, 8]
i: int = 0
names.walk(name) {
    print("${name.rpad(12)}${"${scores[i]}".lpad(4)}")
    i = i + 1
}

Output:

Ann           97
Bartholomew  100
Bo             8
  • The width counts characters, like len: "é".lpad(3) adds two spaces.
  • A longer fill repeats, and is cut to fit: "5".lpad(6, "ab") is "ababa5".
  • Text that is already as long as the width, or longer, stays as it is; it is never cut. So does an empty fill.
  • A negative number padded with zeros keeps its - inside: "-5".lpad(3, "0") is "0-5".

Putting it together

fn title_case(text: str): str {
    out: [str] = []
    text.split().walk(word) {
        first: str = word.part(0, 1).upper()
        rest: str = word.part(1, len(word)).lower()
        out[] = "${first}${rest}"
    }
    return out.join(" ")
}

print(title_case("hELLO   wORLD from   tallinn"))

Output:

Hello World From Tallinn

Not available yet

  • + for joining strings: use interpolation, "${a}${b}", or join.
  • Reading one character with s[i]: use s.part(i, i + 1).

See Limitations.