Programming Search⌘K

Taskintro

Pad a string

Also called pad a string, left pad, right pad, padStart, padEnd, rjust, ljust, PadLeft, PadRight, zero padding, leading zeros, fill character, justify text, leftpad.

Pad a string to a width with a fill character, on the left and on the right, with padStart, rjust, PadLeft or a format width. A string that is already wide enough does not change.

Task

Make a string a given width by adding a fill character. Padding on the left puts the text on the right of the field, and padding on the right puts it on the left. Python says: "Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space)"1.

The function pad(s, width, fill) returns two strings:

  1. s with fill added on the left until the length is width;
  2. s with fill added on the right until the length is width.

For example, pad("7", 3, "0") is ("007", "700"), and pad("abc", 6, "*") is ("***abc", "abc***").

If s has width characters or more, both results are s. Padding never cuts text: "The original string is returned if width is less than or equal to len(s)"1.

Padding is the base of text tables, fixed-width records and numbers with leading zeros. The Rosetta Code task Align columns asks to "allow for each word in a column to be either left justified, right justified, or center justified within its column"2, and each of those is a padding.

Solutions

Language Left padding Right padding
Python s.rjust(width, fill) s.ljust(width, fill)
JavaScript, TypeScript s.padStart(width, fill) s.padEnd(width, fill)
Java fill.repeat(n) + s s + fill.repeat(n)
C# s.PadLeft(width, c) s.PadRight(width, c)
Go strings.Repeat(fill, n) + s s + strings.Repeat(fill, n)
Rust fill.repeat(n) + s s + &fill.repeat(n)
C memset and memcpy into a buffer the same
C++ std::string(n, c) + s s + std::string(n, c)
Bash printf '%*s' and a replacement the same

In the table, n is max(0, width - len(s)).

  • Python. rjust and ljust take the fill character. center pads both sides, and zfill pads with zeros after the sign.
  • JavaScript. padStart "pads this string with a given string (repeated and/or truncated, if needed) so that the resulting string has a given length"3. If the width "is less than or equal to str.length, then str is returned as-is"3. The fill can be longer than one character.
  • TypeScript. The same code as JavaScript, with types.
  • Java. String has no pad method. repeat "Returns a string whose value is the concatenation of this string repeated count times"4. String.format("%5s", s) pads with spaces only.
  • C#. PadLeft "right-aligns the characters in this instance by padding them with spaces on the left"5, and an overload takes a fill character. If the width is less than the length, "the method returns a reference to the existing instance"5.
  • Go. strings.Repeat builds the fill. fmt.Sprintf("%*s", width, s) pads with spaces, and the flag - is "pad with spaces on the right rather than the left"6. The flag 0 pads numbers with zeros.
  • Rust. str::repeat builds the fill. format! has a fill too, but the fill character must be written in the format string: "The optional fill character and alignment is provided normally in conjunction with the width parameter"7. So format!("{s:*>6}") works, but a fill from a variable needs repeat.
  • C. C has no string type with padding. The solution writes the fill with memset and copies the text with memcpy, into buffers from the caller. printf("%*s") pads with spaces only.
  • C++. std::string(n, c) makes the fill. In std::format, the "fill-and-align is an optional fill character (which can be any character other than { or }), followed by one of the align options"8, but it is part of the format string, as in Rust.
  • Bash. printf -v p '%*s' n '' makes n spaces, and ${p// /"$fill"} changes them to the fill character.

The Python solution:

def pad(s, width, fill):
    return s.rjust(width, fill), s.ljust(width, fill)


print(pad("7", 3, "0"))
print(pad("abc", 6, "*"))
print(pad("hello", 3, " "))
print("-42".zfill(6), "-42".rjust(6, "0"))
Output
('007', '700')
('***abc', 'abc***')
('hello', 'hello')
-00042 000-42

Edge cases

  • Empty string. The result is only the fill: pad("", 3, "-") is ("---", "---").
  • Width 0 or the exact width. No padding: pad("abcd", 4, ".") is ("abcd", "abcd").
  • A string wider than the width. The string does not change, and nothing is cut.
  • A negative number as text. pad("-42", 6, "0") gives 000-42, because the function does not know that - is a sign. For a number, use a numeric format such as %06d or zfill, which give -00042.
  • A fill that is in the text. pad("aa", 5, "a") is ("aaaaa", "aaaaa"). The two results are the same.
  • Spaces inside the text. They count as characters: pad("a b", 7, ".") is ("....a b", "a b....").

Pitfalls

  • Length is not width on the screen. The contract uses ASCII. With other text, len counts code points in Python, UTF-16 units in JavaScript, Java and C#, and bytes in Go, Rust, C and Bash with a byte locale. "é".padStart(3) can give 2 or 1 spaces for the same letter, and a Chinese character takes 2 columns on a terminal:

This code runs but gives a wrong answer on purpose.

const composed = "\u00e9";
const decomposed = "e\u0301";
const emoji = "\u{1F600}";
// Show each code point outside ASCII as \u{...}.
const show = (t) =>
  [...t].map((c) => (c < "\u0080" ? c : `\\u{${c.codePointAt(0).toString(16)}}`)).join("");
for (const s of [composed, decomposed, emoji]) {
  console.log(show(s.padStart(4, ".")), s.length);
}
Output
...\u{e9} 1
..e\u{301} 2
..\u{1f600} 2

All three strings show as one character on the screen, but the padding is different. For text from people, count grapheme clusters with Intl.Segmenter, or measure the columns with a library.

  • Zero padding of a negative number. Padding the text -42 gives 000-42. Pad the digits and add the sign after, or use a number format.
  • A string padding function that cuts. Some format widths cut: in C, the precision %.3s cuts a string. A width alone never cuts.

Code

The build runs the native tests of each language in a pinned toolchain.

pad.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pad-a-string/.


def pad(s: str, width: int, fill: str) -> tuple[str, str]:
    """Return s padded with fill to width, once on the left and once on the
    right. If s has width characters or more, both results are s."""
    return s.rjust(width, fill), s.ljust(width, fill)


if __name__ == "__main__":
    print(pad("7", 3, "0"))
    print(pad("abc", 6, "*"))
test_pad.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pad-a-string/.

import pytest

from pad import pad

CASES = [
    ("zeros", "7", 3, "0", ("007", "700")),
    ("spaces", "abc", 6, " ", ("   abc", "abc   ")),
    ("stars", "abc", 6, "*", ("***abc", "abc***")),
    ("empty-string", "", 3, "-", ("---", "---")),
    ("width-zero", "abc", 0, " ", ("abc", "abc")),
    ("exact-width", "abcd", 4, ".", ("abcd", "abcd")),
    ("shorter-width", "hello", 3, " ", ("hello", "hello")),
    ("negative-number-text", "-42", 6, "0", ("000-42", "-42000")),
    ("fill-same-as-text", "aa", 5, "a", ("aaaaa", "aaaaa")),
    ("one-char-wide", "x", 1, "_", ("x", "x")),
    ("spaces-inside", "a b", 7, ".", ("....a b", "a b....")),
]


@pytest.mark.parametrize(("name", "s", "width", "fill", "want"), CASES, ids=[c[0] for c in CASES])
def test_pad(name, s, width, fill, want):
    assert pad(s, width, fill) == want
pad.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

#ifndef PAD_HPP
#define PAD_HPP

#include <cstddef>
#include <string>
#include <string_view>
#include <utility>

// Returns s padded with fill to width, once on the left and once on the
// right. If s has width bytes or more, both results are s.
inline std::pair<std::string, std::string> pad(std::string_view s, std::size_t width, char fill) {
    const std::string extra(width > s.size() ? width - s.size() : 0, fill);
    std::string left = extra;
    left += s;
    std::string right(s);
    right += extra;
    return {left, right};
}

#endif
test_pad.cpp 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

#include <cstddef>
#include <cstdio>

#include "pad.hpp"

namespace {

struct test_case {
    const char* name;
    const char* s;
    std::size_t width;
    char fill;
    const char* left;
    const char* right;
};

const test_case cases[] = {
    {"zeros", "7", 3, '0', "007", "700"},
    {"spaces", "abc", 6, ' ', "   abc", "abc   "},
    {"stars", "abc", 6, '*', "***abc", "abc***"},
    {"empty-string", "", 3, '-', "---", "---"},
    {"width-zero", "abc", 0, ' ', "abc", "abc"},
    {"exact-width", "abcd", 4, '.', "abcd", "abcd"},
    {"shorter-width", "hello", 3, ' ', "hello", "hello"},
    {"negative-number-text", "-42", 6, '0', "000-42", "-42000"},
    {"fill-same-as-text", "aa", 5, 'a', "aaaaa", "aaaaa"},
    {"one-char-wide", "x", 1, '_', "x", "x"},
    {"spaces-inside", "a b", 7, '.', "....a b", "a b...."},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const auto [left, right] = pad(c.s, c.width, c.fill);
        if (left != c.left || right != c.right) {
            std::printf("FAIL %s: got \"%s\" \"%s\"\n", c.name, left.c_str(), right.c_str());
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Pad.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

/** Padding of a string on the left and on the right. */
public final class Pad {
    private Pad() {}

    /**
     * Returns s padded with fill to width: element 0 is padded on the left
     * and element 1 on the right. If s has width characters or more, both
     * elements are s.
     */
    public static String[] pad(String s, int width, String fill) {
        String extra = fill.repeat(Math.max(0, width - s.length()));
        return new String[] {extra + s, s + extra};
    }

    public static void main(String[] args) {
        String[] r = pad("7", 3, "0");
        System.out.println(r[0] + " " + r[1]);
    }
}
PadTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class PadTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("zeros", "7", 3, "0", "007", "700"),
                Arguments.of("spaces", "abc", 6, " ", "   abc", "abc   "),
                Arguments.of("stars", "abc", 6, "*", "***abc", "abc***"),
                Arguments.of("empty-string", "", 3, "-", "---", "---"),
                Arguments.of("width-zero", "abc", 0, " ", "abc", "abc"),
                Arguments.of("exact-width", "abcd", 4, ".", "abcd", "abcd"),
                Arguments.of("shorter-width", "hello", 3, " ", "hello", "hello"),
                Arguments.of("negative-number-text", "-42", 6, "0", "000-42", "-42000"),
                Arguments.of("fill-same-as-text", "aa", 5, "a", "aaaaa", "aaaaa"),
                Arguments.of("one-char-wide", "x", 1, "_", "x", "x"),
                Arguments.of("spaces-inside", "a b", 7, ".", "....a b", "a b....")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void pad(String name, String s, int width, String fill, String left, String right) {
        assertArrayEquals(new String[] {left, right}, Pad.pad(s, width, fill));
    }
}
pad.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

#include "pad.h"

#include <string.h>

void pad(const char *s, size_t width, char fill, char *left, char *right) {
    size_t len = strlen(s);
    size_t extra = width > len ? width - len : 0;
    memset(left, fill, extra);
    memcpy(left + extra, s, len + 1);
    memcpy(right, s, len);
    memset(right + len, fill, extra);
    right[len + extra] = '\0';
}
pad.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

#ifndef PAD_H
#define PAD_H

#include <stddef.h>

// Writes s padded with fill to width into left (padding on the left) and
// into right (padding on the right). If s has width bytes or more, both are
// copies of s. Each buffer must hold max(strlen(s), width) + 1 bytes.
void pad(const char *s, size_t width, char fill, char *left, char *right);

#endif
test_pad.c 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

#include "pad.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    const char *s;
    size_t width;
    char fill;
    const char *left;
    const char *right;
};

static const struct test_case cases[] = {
    {"zeros", "7", 3, '0', "007", "700"},
    {"spaces", "abc", 6, ' ', "   abc", "abc   "},
    {"stars", "abc", 6, '*', "***abc", "abc***"},
    {"empty-string", "", 3, '-', "---", "---"},
    {"width-zero", "abc", 0, ' ', "abc", "abc"},
    {"exact-width", "abcd", 4, '.', "abcd", "abcd"},
    {"shorter-width", "hello", 3, ' ', "hello", "hello"},
    {"negative-number-text", "-42", 6, '0', "000-42", "-42000"},
    {"fill-same-as-text", "aa", 5, 'a', "aaaaa", "aaaaa"},
    {"one-char-wide", "x", 1, '_', "x", "x"},
    {"spaces-inside", "a b", 7, '.', "....a b", "a b...."},
};

int main(void) {
    int failures = 0;
    char left[64];
    char right[64];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        pad(c->s, c->width, c->fill, left, right);
        if (strcmp(left, c->left) != 0 || strcmp(right, c->right) != 0) {
            printf("FAIL %s: got \"%s\" \"%s\"\n", c->name, left, right);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Padding.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

/// <summary>Padding of a string on the left and on the right.</summary>
public static class Padding
{
    /// <summary>
    /// Returns s padded with the first character of fill to width, once on
    /// the left and once on the right. If s has width characters or more,
    /// both results are s.
    /// </summary>
    public static (string Left, string Right) Pad(string s, int width, string fill) =>
        (s.PadLeft(width, fill[0]), s.PadRight(width, fill[0]));
}
PaddingTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

using Xunit;

public sealed class PaddingTests
{
    public static TheoryData<string, string, int, string, string, string> Cases => new()
    {
        { "zeros", "7", 3, "0", "007", "700" },
        { "spaces", "abc", 6, " ", "   abc", "abc   " },
        { "stars", "abc", 6, "*", "***abc", "abc***" },
        { "empty-string", "", 3, "-", "---", "---" },
        { "width-zero", "abc", 0, " ", "abc", "abc" },
        { "exact-width", "abcd", 4, ".", "abcd", "abcd" },
        { "shorter-width", "hello", 3, " ", "hello", "hello" },
        { "negative-number-text", "-42", 6, "0", "000-42", "-42000" },
        { "fill-same-as-text", "aa", 5, "a", "aaaaa", "aaaaa" },
        { "one-char-wide", "x", 1, "_", "x", "x" },
        { "spaces-inside", "a b", 7, ".", "....a b", "a b...." },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Pad(string name, string s, int width, string fill, string left, string right)
    {
        Assert.NotNull(name);
        Assert.Equal((left, right), Padding.Pad(s, width, fill));
    }
}
pad.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

/**
 * Returns s padded with fill to width, once on the left and once on the
 * right. If s has width characters or more, both results are s.
 */
export function pad(s, width, fill) {
  return [s.padStart(width, fill), s.padEnd(width, fill)];
}
pad.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { pad } from "./pad.js";

const cases = [
  ["zeros", "7", 3, "0", ["007", "700"]],
  ["spaces", "abc", 6, " ", ["   abc", "abc   "]],
  ["stars", "abc", 6, "*", ["***abc", "abc***"]],
  ["empty-string", "", 3, "-", ["---", "---"]],
  ["width-zero", "abc", 0, " ", ["abc", "abc"]],
  ["exact-width", "abcd", 4, ".", ["abcd", "abcd"]],
  ["shorter-width", "hello", 3, " ", ["hello", "hello"]],
  ["negative-number-text", "-42", 6, "0", ["000-42", "-42000"]],
  ["fill-same-as-text", "aa", 5, "a", ["aaaaa", "aaaaa"]],
  ["one-char-wide", "x", 1, "_", ["x", "x"]],
  ["spaces-inside", "a b", 7, ".", ["....a b", "a b...."]],
];

for (const [name, s, width, fill, want] of cases) {
  test(name, () => {
    assert.deepEqual(pad(s, width, fill), want);
  });
}
pad.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

/**
 * Returns s padded with fill to width, once on the left and once on the
 * right. If s has width characters or more, both results are s.
 */
export function pad(s: string, width: number, fill: string): [string, string] {
  return [s.padStart(width, fill), s.padEnd(width, fill)];
}
pad.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { pad } from "./pad.ts";

const cases: [string, string, number, string, [string, string]][] = [
  ["zeros", "7", 3, "0", ["007", "700"]],
  ["spaces", "abc", 6, " ", ["   abc", "abc   "]],
  ["stars", "abc", 6, "*", ["***abc", "abc***"]],
  ["empty-string", "", 3, "-", ["---", "---"]],
  ["width-zero", "abc", 0, " ", ["abc", "abc"]],
  ["exact-width", "abcd", 4, ".", ["abcd", "abcd"]],
  ["shorter-width", "hello", 3, " ", ["hello", "hello"]],
  ["negative-number-text", "-42", 6, "0", ["000-42", "-42000"]],
  ["fill-same-as-text", "aa", 5, "a", ["aaaaa", "aaaaa"]],
  ["one-char-wide", "x", 1, "_", ["x", "x"]],
  ["spaces-inside", "a b", 7, ".", ["....a b", "a b...."]],
];

for (const [name, s, width, fill, want] of cases) {
  test(name, () => {
    assert.deepEqual(pad(s, width, fill), want);
  });
}
pad.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

// Package pad pads a string on the left and on the right.
package pad

import "strings"

// Pad returns s padded with fill to width, once on the left and once on the
// right. If s has width bytes or more, both results are s.
func Pad(s string, width int, fill string) (left, right string) {
	extra := strings.Repeat(fill, max(0, width-len(s)))
	return extra + s, s + extra
}
pad_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

package pad

import "testing"

var cases = []struct {
	name, s     string
	width       int
	fill        string
	left, right string
}{
	{"zeros", "7", 3, "0", "007", "700"},
	{"spaces", "abc", 6, " ", "   abc", "abc   "},
	{"stars", "abc", 6, "*", "***abc", "abc***"},
	{"empty-string", "", 3, "-", "---", "---"},
	{"width-zero", "abc", 0, " ", "abc", "abc"},
	{"exact-width", "abcd", 4, ".", "abcd", "abcd"},
	{"shorter-width", "hello", 3, " ", "hello", "hello"},
	{"negative-number-text", "-42", 6, "0", "000-42", "-42000"},
	{"fill-same-as-text", "aa", 5, "a", "aaaaa", "aaaaa"},
	{"one-char-wide", "x", 1, "_", "x", "x"},
	{"spaces-inside", "a b", 7, ".", "....a b", "a b...."},
}

func TestPad(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			left, right := Pad(c.s, c.width, c.fill)
			if left != c.left || right != c.right {
				t.Fatalf("Pad(%q, %d, %q) = (%q, %q), want (%q, %q)", c.s, c.width, c.fill, left, right, c.left, c.right)
			}
		})
	}
}
pad.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

/// Returns s padded with fill to width, once on the left and once on the
/// right. If s has width bytes or more, both results are s.
pub fn pad(s: &str, width: usize, fill: &str) -> (String, String) {
    let extra = fill.repeat(width.saturating_sub(s.len()));
    (format!("{extra}{s}"), format!("{s}{extra}"))
}
tests/pad_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pad-a-string/.

use algo_pad_a_string::pad;

const CASES: &[(&str, &str, usize, &str, (&str, &str))] = &[
    ("zeros", "7", 3, "0", ("007", "700")),
    ("spaces", "abc", 6, " ", ("   abc", "abc   ")),
    ("stars", "abc", 6, "*", ("***abc", "abc***")),
    ("empty-string", "", 3, "-", ("---", "---")),
    ("width-zero", "abc", 0, " ", ("abc", "abc")),
    ("exact-width", "abcd", 4, ".", ("abcd", "abcd")),
    ("shorter-width", "hello", 3, " ", ("hello", "hello")),
    ("negative-number-text", "-42", 6, "0", ("000-42", "-42000")),
    ("fill-same-as-text", "aa", 5, "a", ("aaaaa", "aaaaa")),
    ("one-char-wide", "x", 1, "_", ("x", "x")),
    ("spaces-inside", "a b", 7, ".", ("....a b", "a b....")),
];

#[test]
fn cases() {
    for &(name, s, width, fill, (left, right)) in CASES {
        assert_eq!(pad(s, width, fill), (left.to_owned(), right.to_owned()), "{name}");
    }
}
pad.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pad-a-string/.

# _pad_extra width s fill: set the variable extra to fill repeated
# max(0, width - length of s) times.
_pad_extra() {
  local n=$(($1 - ${#2}))
  extra=''
  if ((n > 0)); then
    printf -v extra '%*s' "$n" ''
    extra=${extra// /"$3"}
  fi
}

# pad_left s width fill: print s padded with fill on the left to width.
pad_left() {
  local extra
  _pad_extra "$2" "$1" "$3"
  printf '%s\n' "$extra$1"
}

# pad_right s width fill: print s padded with fill on the right to width.
pad_right() {
  local extra
  _pad_extra "$2" "$1" "$3"
  printf '%s\n' "$1$extra"
}
test_pad.bats 19 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pad-a-string/.

setup() {
  source "$BATS_TEST_DIRNAME/pad.sh"
}

@test "zeros" { run pad_left '7' 3 '0'; [ "$output" = '007' ]; run pad_right '7' 3 '0'; [ "$output" = '700' ]; }
@test "spaces" { run pad_left 'abc' 6 ' '; [ "$output" = '   abc' ]; run pad_right 'abc' 6 ' '; [ "$output" = 'abc   ' ]; }
@test "stars" { run pad_left 'abc' 6 '*'; [ "$output" = '***abc' ]; run pad_right 'abc' 6 '*'; [ "$output" = 'abc***' ]; }
@test "empty-string" { run pad_left '' 3 '-'; [ "$output" = '---' ]; run pad_right '' 3 '-'; [ "$output" = '---' ]; }
@test "width-zero" { run pad_left 'abc' 0 ' '; [ "$output" = 'abc' ]; run pad_right 'abc' 0 ' '; [ "$output" = 'abc' ]; }
@test "exact-width" { run pad_left 'abcd' 4 '.'; [ "$output" = 'abcd' ]; run pad_right 'abcd' 4 '.'; [ "$output" = 'abcd' ]; }
@test "shorter-width" { run pad_left 'hello' 3 ' '; [ "$output" = 'hello' ]; run pad_right 'hello' 3 ' '; [ "$output" = 'hello' ]; }
@test "negative-number-text" { run pad_left '-42' 6 '0'; [ "$output" = '000-42' ]; run pad_right '-42' 6 '0'; [ "$output" = '-42000' ]; }
@test "fill-same-as-text" { run pad_left 'aa' 5 'a'; [ "$output" = 'aaaaa' ]; run pad_right 'aa' 5 'a'; [ "$output" = 'aaaaa' ]; }
@test "one-char-wide" { run pad_left 'x' 1 '_'; [ "$output" = 'x' ]; run pad_right 'x' 1 '_'; [ "$output" = 'x' ]; }
@test "spaces-inside" { run pad_left 'a b' 7 '.'; [ "$output" = '....a b' ]; run pad_right 'a b' 7 '.'; [ "$output" = 'a b....' ]; }

References

  1. Built-in Types, Python documentation, str.rjust; str.ljust; str.zfill
  2. Rosetta Code, Align columns (task text, from acmeism/RosettaCodeData), task text
  3. String.prototype.padStart(), MDN Web Docs, Description; Parameters
  4. Class String, Java SE 25 API, repeat
  5. String.PadLeft Method, .NET API, Overloads; Remarks
  6. Package fmt, The Go Standard Library, Printing; Other flags
  7. Module std::fmt, The Rust Standard Library, Fill/Alignment
  8. Standard format specification, C++ reference, cppreference.com, Fill and align

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source