<p>I have multiple lines to format in a loop</p>
<p><code>
for k, v := range fooArray {
fmt.Printf("foo: %v, count: %v", k, fooArray[k])
}
</code>
but keys have different length, and count value can't be aligned. How to format in this case?</p>
<hr/>**评论:**<br/><br/>pdffs: <pre><p><a href="https://golang.org/pkg/text/tabwriter/" rel="nofollow">https://golang.org/pkg/text/tabwriter/</a></p>
<p>handles tabular output.</p></pre>lespritd: <pre><p>In order to align, you can feed <code>fmt.Printf</code> additional directions. Specifically, <code>%ABv</code> tells Printf to pad the value v with up to B instances of rune A. This only works with some values of A, specifically, '0' and ' ' work.</p>
<p>For example:</p>
<pre><code>for _, v := range []int{1, 12, 123} {
fmt.Printf("%03v\n", v)
}
// outputs:
// 001
// 012
// 123
for _, v := range []int{1, 12, 123} {
fmt.Printf("% 3v\n", v)
}
// outputs:
// 1
// 12
// 123
</code></pre>
<p><a href="https://play.golang.org/p/u9NMaHMv6sI" rel="nofollow">https://play.golang.org/p/u9NMaHMv6sI</a></p></pre>jerf: <pre><p>I'm on my phone so I can't give examples, but have a careful read of <a href="https://golang.org/pkg/fmt/" rel="nofollow">https://golang.org/pkg/fmt/</a> , looking for the phrase "Width is specified by an optional decimal number immediately preceding the verb".</p></pre>marksteve4: <pre><p>it's not fixed width. What i want: </p>
<p>key1: 123 count 1</p>
<p>key2: 12 count 2 (sorry I don't know how to format this in reddit. but count is supposed to be aligned)</p>
<p>fixed width:</p>
<p>key1: 123 count 1</p>
<p>key2: 012 count 2</p></pre>TheSpanishImposition: <pre><p><a href="https://play.golang.org/p/kB7vOr4JgMC" rel="nofollow">Like this?</a></p>
<pre><code>foo: 123 count: 1
foo: 12 count: 2
foo: 123 count: 1
foo: 12 count: 2
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传