1#' Zero-pad a string. 2#' 3#' Return a copy of the string left filled with ASCII \code{'0'} digits to make 4#' a string of length \code{width}. 5#' 6#' A leading sign prefix (+/-) is handled by inserting the padding after 7#' the sign character rather than before. The original string is returned if 8#' \code{width} is less than or equal to \code{nchar(str)}. 9#' 10#' @param str A character vector. 11#' @param width An integer. 12#' 13#' @return A character vector. 14#' 15#' @references \url{https://docs.python.org/3/library/stdtypes.html#str.zfill} 16#' 17#' @examples 18#' pystr_zfill("42", 5) 19#' pystr_zfill("-42", 5) 20#' pystr_zfill("+42", 5) 21#' 22#' @export 23pystr_zfill <- function(str, width) { 24 return(vapply(str, function(x) pystr_zfill_(x, width), character(1), USE.NAMES = FALSE)) 25} 26 27pystr_zfill_ <- function(str, width) { 28 if(width <= nchar(str)) { 29 return(str) 30 } 31 32 filled = str 33 first_char = substr(filled, 1, 1) 34 35 if(first_char %in% c("-", "+")) { 36 filled = substr(filled, 2, nchar(filled)) 37 } else { 38 first_char = "" 39 } 40 41 zeros = pystr_join(rep(0, width - nchar(str)), "") 42 return(pystr_join(c(first_char, zeros, filled), "")) 43} 44