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.
- Evidence
- Code in 10 languages
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:
swithfilladded on the left until the length iswidth;swithfilladded on the right until the length iswidth.
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.
rjustandljusttake the fill character.centerpads both sides, andzfillpads 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.
Stringhas 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.Repeatbuilds 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 flag0pads numbers with zeros. - Rust.
str::repeatbuilds 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. Soformat!("{s:*>6}")works, but a fill from a variable needsrepeat. - C. C has no string type with padding. The solution writes the fill with
memsetand copies the text withmemcpy, into buffers from the caller.printf("%*s")pads with spaces only. - C++.
std::string(n, c)makes the fill. Instd::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 ''makesnspaces, 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"))
('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")gives000-42, because the function does not know that-is a sign. For a number, use a numeric format such as%06dorzfill, 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,
lencounts 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);
}
...\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
-42gives000-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
%.3scuts a string. A width alone never cuts.
Related tasks
- Print formatted output: format widths pad each column.
- Format specifiers: the fill, the alignment and the width in a format string.
Code
The build runs the native tests of each language in a pinned toolchain.
# 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
// 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;
}
// 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));
}
}
// 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;
}
// 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));
}
}
// 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);
});
}
// 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);
});
}
// 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)
}
})
}
}
// 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}");
}
}
#!/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
- Built-in Types, Python documentation, str.rjust; str.ljust; str.zfill
- Rosetta Code, Align columns (task text, from acmeism/RosettaCodeData), task text
- String.prototype.padStart(), MDN Web Docs, Description; Parameters
- Class String, Java SE 25 API, repeat
- String.PadLeft Method, .NET API, Overloads; Remarks
- Package fmt, The Go Standard Library, Printing; Other flags
- Module std::fmt, The Rust Standard Library, Fill/Alignment
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 30T0B3 Edit this page History Report an error Markdown