pystr_format: Format a string.

Description Usage Arguments Details Value References Examples

View source: R/pystr_format.R

Description

Perform a string formatting operation.

Usage

1

Arguments

str

A character vector.

...

Parameter values. See details and examples

Details

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.

Value

A character vector.

References

https://docs.python.org/3/library/stdtypes.html#str.format

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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)

nicolewhite/pystr documentation built on May 23, 2019, 5:09 p.m.