sprintf()

sprintf(fmt, ...)
Returns: character · Updated March 13, 2026 · Base Functions
string-formatting sprintf base

sprintf() formats strings using C-style format specifiers. It takes a format string containing placeholders and substitutes values into them.

Syntax

sprintf(fmt, ...)

Parameters

ParameterTypeDefaultDescription
fmtcharacterFormat string containing format specifiers
...anyValues to substitute into the format string

Format Specifiers

The key format specifiers are:

SpecifierMeaningExample
%sString"%s"
%dInteger"%d"
%fFixed-point number"%.2f"
%eScientific notation"%e"
%%Literal percent sign"%%"

Examples

Basic string substitution

sprintf("Hello, %s!", "World")
# [1] "Hello, World!"

name <- "Alice"
sprintf("Welcome, %s!", name)
# [1] "Welcome, Alice!"

Numeric formatting

sprintf("The value is %d", 42)
# [1] "The value is 42"

sprintf("Pi to 3 decimals: %.3f", pi)
# [1] "Pi to 3 decimals: 3.142"

sprintf("Scientific: %e", 1234)
# [1] "Scientific: 1.234000e+03"

Multiple values

sprintf("%s has %d points", "Player", 100)
# [1] "Player has 100 points"

sprintf("Item: %s, Price: $%.2f, Qty: %d", "Widget", 19.99, 5)
# [1] "Item: Widget, Price: $19.99, Qty: 5"

Padding and width

sprintf("%10s", "test")
# [1] "      test"

sprintf("%05d", 42)
# [1] "00042"

Common Patterns

Building file paths

filename <- "data"
extension <- "csv"
sprintf("%s.%s", filename, extension)
# [1] "data.csv"

Creating messages

n <- 150
total <- 500
sprintf("Processed %d of %d items (%.1f%%)", n, total, n/total*100)
# [1] "Processed 150 of 500 items (30.0%)"

Dynamic labels

sprintf("Iteration %03d complete", 5)
# [1] "Iteration 005 complete"

See Also