1#' Partition a string. 2#' 3#' Split the string at the first occurrence of \code{sep}, and return a list of character vectors containing the part 4#' before the separator, the separator itself, and the part after the separator. 5#' 6#' If the separator is not found, return a character vector containing the string itself, followed by two empty strings. 7#' 8#' @param str A character vector. 9#' @param sep A character string. 10#' 11#' @return A list of character vectors. 12#' 13#' @references \url{https://docs.python.org/3/library/stdtypes.html#str.partition} 14#' 15#' @seealso \code{\link{pystr_rpartition}} 16#' 17#' @examples 18#' pystr_partition("onetwothreeonetwothree", "two") 19#' 20#' @export 21pystr_partition <- function(str, sep) { 22 return(mapply(pystr_partition_, str, sep, SIMPLIFY=FALSE, USE.NAMES=FALSE)) 23} 24pystr_partition_ <- function(str, sep) { 25 if(sep == "") { 26 stop("Empty separator.") 27 } 28 29 idx = pystr_find(str, sep) 30 31 if(idx == -1) { 32 return(c(str, "", "")) 33 } 34 35 before = substr(str, 1, idx - 1) 36 after = substr(str, idx + nchar(sep), nchar(str)) 37 return(c(before, sep, after)) 38} 39