Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Strings

Strings are immutable sequences of characters. All string methods return new strings — the original is never modified.

Creating strings

let s = "hello world"
let empty = ""
let escaped = "Line 1\nLine 2"

Supported escape sequences: \", \\, \n, \t, \{, \}.

Indexing

let s = "hello"
print(s[0])      // "h"
print(s[-1])     // "o"

Each index returns a single-character string (there’s no separate character type).

String interpolation

Insert variable values with {name} inside a string:

let name = "Alice"
let count = 5
print("Hello, {name}! You have {count} items.")

Only variable names are allowed inside {}. For expressions, use a temporary variable:

let total = str(count * 2)
print("Double: {total}")

Or use concatenation:

print("Double: " + str(count * 2))

To include a literal { or } in a string, escape it with \{ and \}:

print("Use \{name\} for interpolation")
// prints: Use {name} for interpolation

Concatenation

Use + to join strings:

let full = "Hello" + ", " + "world!"
print(full)    // "Hello, world!"

Numbers must be converted with str() first:

let msg = "Score: " + str(42)

Methods

MethodReturnsDescription
s.len()numberNumber of characters
s.contains(sub)boolWhether the string contains sub
s.starts_with(prefix)boolWhether it starts with prefix
s.ends_with(suffix)boolWhether it ends with suffix
s.index_of(sub)number or noneIndex of first occurrence, or none
s.split(sep)arraySplit into array of strings on sep
s.replace(old, new)stringReplace all occurrences
s.upper()stringUppercase copy
s.lower()stringLowercase copy
s.trim()stringCopy with leading/trailing whitespace removed
s.slice(start, end)stringSubstring (both args optional)

Practical examples

Parsing CSV data

let input = "Alice,95,A"
let parts = input.split(",")
print(parts[0])    // "Alice"
print(parts[1])    // "95"

Checking prefixes

let filename = "report.csv"
if filename.ends_with(".csv") {
  print("CSV file detected")
}

Building a formatted string

let items = ["apple", "banana", "cherry"]
let count = str(items.len())
let list = items.join(", ")
print("Found {count} items: {list}")