如果我想填充一个字符串,我可以使用这样的东西:
https://play.golang.org/p/ATeUhSP18N
package main
import (
"fmt"
)
func main() {
x := fmt.Sprintf("%+20s", "Hello World!")
fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)
+ always print a sign for numeric values;
guarantee ASCII-only output for %q (%+q)
- pad with spaces on the right rather than the left (left-justify the field)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想动态更改打击垫大小,我怎么能传递该值?
我的第一位客人是:
x := fmt.Sprintf("%+%ds", 20, "Hello World!")
Run Code Online (Sandbox Code Playgroud)
但我明白了:
%ds%!(EXTRA int=20, string=Hello World!)
Run Code Online (Sandbox Code Playgroud)
有没有办法在不创建自定义填充函数的情况下执行此操作,可能会使用for循环向左或向右添加空格:
for i := 0; i < n; i++ {
out += str
}
Run Code Online (Sandbox Code Playgroud)
dol*_*men 11
使用*告诉Sprintf得到从参数列表的格式化参数:
fmt.Printf("%*s\n", 20, "Hello World!")
Run Code Online (Sandbox Code Playgroud)
请访问:https: //golang.org/pkg/fmt/ 并向下滚动,直至找到:
Run Code Online (Sandbox Code Playgroud)fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)相当于
Run Code Online (Sandbox Code Playgroud)fmt.Sprintf("%6.2f", 12.0)将产生"12.00".因为显式索引会影响后续动词,所以通过重置要重复的第一个参数的索引,可以使用此表示法多次打印相同的值
这听起来像你想要的.
使用参数设置字段宽度和精度的描述的真正核心在上面进一步说明:
宽度和精度以Unicode代码点为单位测量,即符文.(这与C的printf不同,其中单位总是以字节为单位进行测量.)其中一个或两个标志可以用字符'*'替换,导致它们的值从下一个操作数获得,该操作数必须是int类型.
上面的例子只是在参数列表中使用显式索引,这有时很好,并允许您重复使用相同的宽度和精度值来进行更多转换.
所以你也可以写:
fmt.Sprintf("*.*f", 6, 2, 12.0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2062 次 |
| 最近记录: |