Format a string.

Perform a string formatting operation.

pystr_format(str, ...)
A character vector.
Parameter values. See details and examples

The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

If ... is a single argument of a data.frame-like object, pystr_format will return an nrow()-length character vector using the column names of the data.frame for the named {placeholder}s.


A character vector.


  • pystr_format
# Numeric placeholders

pystr_format("Hello {1}, my name is {2}.", "World", "Nicole")
pystr_format("Hello {1}, my name is {2}.", c("World", "Nicole"))
pystr_format("Hello {1}, my name is {2}.", list("World", "Nicole"))

# Named placeholders

pystr_format("Hello {thing}, my name is {name}.", thing="World", name="Nicole")
pystr_format("Hello {thing}, my name is {name}.", c(thing="World", name="Nicole"))
pystr_format("Hello {thing}, my name is {name}.", list(thing="World", name="Nicole"))

# Pass in characters and numbers

pystr_format("Hello {name}, you have {n} new notifications!", name="Nicole", n=2)

## Placeholders can be used more than once

pystr_format("The name is {last}. {first} {last}.", last="Bond", first="James")

## Pass in a whole data frame, matching by column names

my_cars <- data.frame(car=rownames(mtcars), mtcars)
head(pystr_format("The {car} gets {mpg} mpg (hwy) despite having {cyl} cylinders.", my_cars))

supers <- data.frame(first=c("Bruce", "Hal", "Clark", "Diana"),
                     last=c("Wayne", "Jordan", "Kent", "Prince"),
                     is=c("Batman", "Green Lantern", "Superman", "Wonder Woman"))
pystr_format("{first} {last} is really {is} but you shouldn't call them {first} in public.", supers)
Documentation reproduced from package pystr, version 2.0.0, License: MIT + file LICENSE

Community examples

Looks like there are no examples yet.