以编程方式将字符串宽度值插入 sprintf() [英] Programmatically insert string width value into sprintf()
本文介绍了以编程方式将字符串宽度值插入 sprintf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以编程方式将字符串宽度值插入到 sprintf()
格式中.
I am trying to programmatically insert the string width value into a sprintf()
format.
想要的结果是
sprintf("%-20s", "hello")
# [1] "hello "
但我想在同一个调用中即时插入 20
,以便它可以是任何数字.我试过了
But I want to insert the 20
on the fly, in the same call, so that it can be any number. I have tried
sprintf("%%-%ds", 20, "hello")
# [1] "%-20s"
sprintf("%-%ds", 20, "hello")
# Error in sprintf("%-%ds", 20, "hello") :
# invalid format '%-%d'; use format %f, %e, %g or %a for numeric objects
sprintf("%-%%ds", 20, "hello")
# Error in sprintf("%-%%ds", 20, "hello") :
# invalid format '%-%%d'; use format %f, %e, %g or %a for numeric objects
这在 sprintf()
中可行吗?
推荐答案
是的,这可以通过使用星号 *
来实现.
Yes, This is possible by using the asterisk *
.
如文档中所述,
一个字段的宽度或精度(但不是两者)可以用星号 * 表示:在这种情况下,一个参数指定了所需的数字
A field width or precision (but not both) may be indicated by an asterisk *: in this case an argument specifies the desired number
因此代码是
> sprintf("%-*s", 20, "hello")
[1] "hello "
这篇关于以编程方式将字符串宽度值插入 sprintf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文