本文介绍了格式化数字为固定宽度,前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下代码 a b 产生这个输出: / b> name_1name_26name_51name_76name_101 我想要所有值的宽度相同,这意味着我用这样的零填充值: name_001name_026name_051name_076name_101 如何处理? (这个问题与 this one 。) 其中一个是使用 sprintf 。它使用嵌入在字符串中的 C 样式格式代码来表示传递给它的任何其他参数的格式。例如,格式化代码%3d 表示格式化一个宽度为3的整数: a sprintf(name_%03d,a) [1]name_001name_026name_051name_076name_101 另一个是 formatC 和 [1]name_001name_026name_051name_076name_101 The following codea <- seq(1,101,25)b <- paste("name", 1:length(a), sep = "_")produces this output:"name_1" "name_26" "name_51" "name_76" "name_101"I'd like to have the same width of all values which means for me to fill the values with zeros like this:"name_001" "name_026" "name_051" "name_076" "name_101"How do I handle that?(This question is related to this one.) 解决方案 There are several solutions to this.One of them is to use sprintf. This uses C style formatting codes embedded in a character string to indicate the format of any other arguments passed to it. For example, the formatting code %3d means format a number as integer of width 3:a <- seq(1,101,25)sprintf("name_%03d", a)[1] "name_001" "name_026" "name_051" "name_076" "name_101"Another is formatC and paste:paste("name", formatC(a, width=3, flag="0"), sep="_")[1] "name_001" "name_026" "name_051" "name_076" "name_101" 这篇关于格式化数字为固定宽度,前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!