stringr::str_pad()

str_pad(string, width, side = c("left", "right", "both"), pad = " ")
Returns: character · Updated March 16, 2026 · Tidyverse
stringr string padding formatting tidyverse

The str_pad() function from stringr pads a string to a specified width by adding filler characters. It is useful for aligning text, creating fixed-width output, and formatting data for display or export.

Syntax

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

Parameters

ParameterTypeDefaultDescription
stringcharacterRequiredA character vector to pad
widthnumericRequiredMinimum width of the resulting string
sidecharacter”left”Which side to pad: “left”, “right”, or “both”
padcharacter” “Character to use for padding

Examples

Basic usage

library(stringr)

# Pad strings to width 10 on the left (default)
str_pad(c("apple", "banana", "cherry"), width = 10)
# [1] "     apple" "    banana" "   cherry"

Pad on the right

# Pad on the right side
str_pad(c("apple", "banana", "cherry"), width = 10, side = "right")
# [1] "apple     " "banana    " "cherry    "

Pad on both sides

# Center the string by padding both sides
str_pad(c("apple", "banana"), width = 10, side = "both")
# [1] "  apple   " "  banana  "

Use a custom padding character

# Pad with zeros
str_pad("123", width = 6, pad = "0")
# [1] "000123"

# Pad with dashes
str_pad("test", width = 8, pad = "-")
# [1] "----test"

Working with numeric values

# Format numbers with leading zeros
nums <- c(1, 23, 456, 7890)
str_pad(nums, width = 5, pad = "0")
# [1] "00001" "00023" "00456" "78900"

Combining with other stringr functions

# Trim and then pad to ensure consistent width
strings <- c("  hello  ", "world", "  test  ")
str_pad(str_trim(strings), width = 10)
# [1] "     hello" "     world" "      test"

Common Use Cases

  • Data alignment: Create aligned table output
  • Fixed-width format: Prepare data for fixed-width file formats
  • Number formatting: Add leading zeros to identifiers or numbers
  • Text justification: Left, right, or center text alignment

Creating a formatted table

library(dplyr)

df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  score = c(95, 87, 100)
)

df %>%
  mutate(
    name = str_pad(name, width = 10, side = "right"),
    score = str_pad(as.character(score), width = 3, pad = "0", side = "left")
  )
#      name   score
# 1 Alice     095
# 2 Bob       087
# 3 Charlie   100

Preparing for fixed-width files

# Ensure each field has a fixed width for fixed-width format
data <- data.frame(
  id = str_pad(1:3, width = 5, pad = "0"),
  value = str_pad(c("A", "BB", "CCC"), width = 5, pad = " ")
)

paste0(data$id, data$value)
# [1] "00001    A" "00002   BB" "00003  CCC"

See Also