Golang 字符串填充示例
填充概述
Go (Golang) 中的字符串填充指的是在字符串前添加或附加空格或字符的操作,这样无论输入字符串的长度如何,最终字符串的总长度都是固定的。 我们可能遇到过这样一种情况,我们必须以这种方式显示或格式化数据,使其像在表格中一样对齐。 让我们看一个例子
athletes distances
john 10km
marylin 131km
joe 0.5km
arthur 1km
athletes
向左对齐,距离向右对齐。 在 Go (Golang) 中,填充可以仅使用标准库来完成,而无需自己编写填充逻辑或导入第三方库。
使用 fmt 包进行填充和格式化
在 Go (Golang) 中,我们可以使用 fmt
包向字符串添加填充。 我们可以使用 fmt
包中定义的宽度选项。
宽度由动词前的可选十进制数指定。 如果缺省
- %f 默认宽度,默认精度
- %9f 宽度 9,默认精度
- %.2f 默认宽度,精度2
- %9.2f 宽度 9,精度 2
- %9.f 宽度 9,精度 0
让我们看一些例子
右填充
fmt.Println("'%-4s'", "john")
运行结果如下
'john '
左填充
fmt.Println("'%4dkm'", 10)
运行结果如下
' 10km'
用零填充
fmt.Println("'%04dkm'", 10)
运行结果如下
'000010km'
任意长度的填充
我们还可以使用星号定义填充宽度并指定表示填充长度的参数。
fmt.Println("'%*dkm'", 10, 2)
运行结果如下
' 2km'
更多格式化指令
我们可以在官方文档页面中查看更多使用 fmt
包时可以应用的格式化指令
+ 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)
# alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
for %q, print a raw (backquoted) string if strconv.CanBackquote
returns true;
always print a decimal point for %e, %E, %f, %F, %g and %G;
do not remove trailing zeros for %g and %G;
write e.g. U+0078 'x' if the character is printable for %U (%#U).
' ' (space) leave a space for elided sign in numbers (% d);
put spaces between bytes printing strings or slices in hex (% x, % X)
0 pad with leading zeros rather than spaces;
for numbers, this moves the padding after the sign
```
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。