How do I pad a string to a fixed width in EK9?
← Common String Operations · Ref: Q176
EK9 strings have .leftPadded(n) and .rightPadded(n) methods for padding to a fixed width.
RIGHT PADDED
Pad with spaces on the right to reach width n:
padded <- myString.rightPadded(20)
Useful for left-aligned columns. If the string is already longer than n, it is returned unchanged.
LEFT PADDED
Pad with spaces on the left to reach width n:
padded <- myString.leftPadded(20)
Useful for right-aligned columns.
FORMATTING COLUMNS
Combine padding for tabular output:
stdout.println(`${name.rightPadded(15)} ${score.leftPadded(5)}`)
See Q37 for comprehensive string operations. See Q173 for trim (the complement of padding).
Example
defines module qa.stringops.padding defines program StringPaddingDemo() stdout <- Stdout() // === RIGHT PADDED (left-aligned) === word <- "Hello" rightPad <- word.rightPadded(20) stdout.println(`Right padded: [${rightPad}]`) // === LEFT PADDED (right-aligned) === leftPad <- word.leftPadded(20) stdout.println(`Left padded: [${leftPad}]`) // === FORMATTING COLUMNS === names <- ["Alice", "Bob", "Charlie"] amounts <- ["1234", "56", "789"] idx <- 0 for name in names amount <- amounts.getOrDefault(idx, "0") stdout.println(`${name.rightPadded(12)} ${amount.leftPadded(8)}`) idx := idx + 1 // === STRING LONGER THAN WIDTH === longStr <- "A very long string" padded <- longStr.rightPadded(5) stdout.println(`Long string padded to 5: [${padded}]`)
Common mistakes
E50060 — String has no padEnd() method. The correct method names in EK9 are rightPadded() and leftPadded(). See ek9 -h E50060 for details.
Incorrect:
rightPad <- word.padEnd(20)
Correct:
rightPad <- word.rightPadded(20)
E11068 — Concatenating 3 or more string parts with + triggers E11068. Use backtick interpolation instead. See ek9 -h E11068 for details.
Incorrect:
stdout.println(name.rightPadded(12) + " " + amount.leftPadded(8))
Correct:
stdout.println(`${name.rightPadded(12)} ${amount.leftPadded(8)}`)
Other ways to ask this
- How do I align text to a fixed column width in EK9?
- What is the EK9 equivalent of string padding?
- How do I right-align or left-align text in EK9?
Coming from another language?
Java: String.format("%-20s", str) for left-align, String.format("%20s", str) for right-align. Python: str.ljust(20), str.rjust(20). Rust: format!("{:<20}", str), format!("{:>20}", str). Go: fmt.Sprintf("%-20s", str). JavaScript: str.padEnd(20), str.padStart(20). Kotlin: str.padEnd(20), str.padStart(20). EK9: str.rightPadded(20), str.leftPadded(20).
Keywords: right, string, fixed, text, align, width, column, left, pad, format, padding