aligned string format

blov · · 331 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have multiple lines to format in a loop</p> <p><code> for k, v := range fooArray { fmt.Printf(&#34;foo: %v, count: %v&#34;, k, fooArray[k]) } </code> but keys have different length, and count value can&#39;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, &#39;0&#39; and &#39; &#39; work.</p> <p>For example:</p> <pre><code>for _, v := range []int{1, 12, 123} { fmt.Printf(&#34;%03v\n&#34;, v) } // outputs: // 001 // 012 // 123 for _, v := range []int{1, 12, 123} { fmt.Printf(&#34;% 3v\n&#34;, 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&#39;m on my phone so I can&#39;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 &#34;Width is specified by an optional decimal number immediately preceding the verb&#34;.</p></pre>marksteve4: <pre><p>it&#39;s not fixed width. What i want: </p> <p>key1: 123 count 1</p> <p>key2: 12 count 2 (sorry I don&#39;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

331 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传