简体   繁体   中英

Lua: string of specific length

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

defines foo as a string of specific length

"                                  here is a string 00012"

However, is there an easy way to get

"here is a string                                   00012"

I know, that I can fill up the string data with spaces

while data:len() < 50 do data = data.." " end

Add a minus to format string %-50s to align text to the left:

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

Output:

56  here is a string                                   00012

Allowed flags:

- : left align result inside field
+ : always prefix with a sign, using + if field positive
0 : left-fill with zeroes rather than spaces
(space) : If positive, put a space where the + would have been
# : Changes the behaviour of various formats, as follows:
  For octal conversion (o), prefixes the number with 0 - if necessary.
  For hex conversion (x), prefixes the number with 0x
  For hex conversion (X), prefixes the number with 0X
  For e, E and f formats, always show the decimal point.
  For g and G format, always show the decimal point, and do not truncate trailing zeroes.
  The option to 'always show the decimal point' would only apply if you had the precision set to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM