Logo

Programming-Idioms

  • Go
  • Python

Idiom #215 Pad string on the left

Prepend extra character c at the beginning of string s to make sure its length is at least m.
The length is the number of characters, not the number of bytes.

s = s.rjust(m, c)
s = f'{s:{c}>{m}}'
import "strings"
import "utf8"
if n := utf8.RuneCountInString(s); n < m {
	s = strings.Repeat(c, m-n) + s
}

c here is a one-character string
s = s.PadLeft(m, c);

New implementation...