String, list, dict methods and chaining
Learning objective
- Apply method calls and chaining to produce compact readable code.
Key syntax
let text: string = " Lucia Lang ";
let parts: list<string> = text.trim().lower().split(" ");
Examples
- String methods:
upper, lower, trim, ltrim, rtrim, split, join, contains, starts_with, ends_with, replace, indexOf, repeat, substring, pad_left, pad_right, to_int, to_float, to_bool, count, capitalize, title, is_numeric, is_alpha, is_alnum.
- List methods:
append, pop, contains, sort, reverse, indexOf, slice, clear, insert, remove, removeAt, extend, first, last, is_empty, copy.
- Dict methods:
keys, values, contains_key, get, clear, remove, items, is_empty, size, merge, put.
Chaining examples
let cleaned: string = " Lucia ".trim().lower();
let words: list<string> = cleaned.split(" ");
let csv: string = ",".join(words);
let nums: list<int> = [3, 1, 2];
nums.sort();
let top2: list<int> = nums.slice(0, 2);
print(top2.contains(2));
Contracts to remember
append takes exactly one item compatible with list<T>.
pop takes no arguments.
get accepts 1 or 2 arguments: key and optional default.
insert requires (index: int, value: T).
removeAt requires (index: int).
extend requires list<T> compatible with receiver.
put requires (key: K, value: V) compatible with dict type.
- Collection size uses
len(x), not .length().
Cross-target note
dict.get(key) differs when key is missing:
- Python target: returns
None
- JavaScript target: returns
undefined
dict.get(key, default) is consistent in both targets.
Common mistakes
- Calling methods that do not belong to the receiver type.
- Forgetting method argument contracts.
Suggested practice
- Normalize a list of names and build a CSV output line.
- types-and-collections
- string-interpolation