Lua: 字符串长度指定

local data = "here is a string"
local no = 12
foo = string.format("%50s %05d",data,no)
print(foo:len(),string.format("%q",foo))

foo 定义为指定长度的字符串

"                                  here is a string 00012"

但是,有没有一种_简单_的方法来得到

"here is a string                                   00012"

我知道,可以使用空格填充字符串 data

while data:len() < 50 do data = data.." " end
点赞
用户7504558
用户7504558

在格式字符串 %-50s 中添加减号来将文本左对齐:

foo = string.format("%-50s %05d","here is a string", 12)
print(foo:len(), foo)

输出结果:

56  here is a string                                   00012

允许使用的标志:

-:在字段内左对齐结果
+:始终以符号为前缀,如果字段为正,则使用+号
0:用零而不是空格进行左填充
(空格):如果是正数,则在+号所在的位置放置一个空格
#:更改各种格式的行为,如下所示:
  对于八进制转换(o),将数字前缀为0-如果必要。
  对于十六进制转换(x),将数字前缀为0x
  对于十六进制转换(X),将数字前缀为0X
  对于e,E和f格式,始终显示小数点。
  对于g和G格式,始终显示小数点,不截断尾部的零。
  如果将精度设置为0,则“始终显示小数点”的选项将仅适用于它。
2018-10-23 12:47:16