簡體   English   中英

Lua:特定長度的字符串

[英]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))

foo定義為特定長度的字符串

"                                  here is a string 00012"

但是,有一種簡單的方法可以獲得

"here is a string                                   00012"

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

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

添加減號以格式化字符串%-50s以將文本對齊到左側:

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

輸出:

56  here is a string                                   00012

允許的標志:

- : 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM