Learn R Programming

stringr (version 1.5.1)

str_pad: Pad a string to minimum width

Description

Pad a string to a fixed width, so that str_length(str_pad(x, n)) is always greater than or equal to n.

Usage

str_pad(
  string,
  width,
  side = c("left", "right", "both"),
  pad = " ",
  use_width = TRUE
)

Value

A character vector the same length as stringr/width/pad.

Arguments

string

Input vector. Either a character vector, or something coercible to one.

width

Minimum width of padded strings.

side

Side on which padding character is added (left, right or both).

pad

Single padding character (default is a space).

use_width

If FALSE, use the length of the string instead of the width; see str_width()/str_length() for the difference.

See Also

str_trim() to remove whitespace; str_trunc() to decrease the maximum width of a string.

Examples

Run this code
rbind(
  str_pad("hadley", 30, "left"),
  str_pad("hadley", 30, "right"),
  str_pad("hadley", 30, "both")
)

# All arguments are vectorised except side
str_pad(c("a", "abc", "abcdef"), 10)
str_pad("a", c(5, 10, 20))
str_pad("a", 10, pad = c("-", "_", " "))

# Longer strings are returned unchanged
str_pad("hadley", 3)

Run the code above in your browser using DataLab