在某些情況下,我們想要格式化字符串以幫助我們以特定格式打印輸出。
當我們使用 string.format() 函數時,它會根據第一個參數 so-called 格式字符串給出的描述,返回其可變數量參數的格式化版本。
我們得到輸出的格式字符串類似於標準 C 的 printf 函數的格式字符串:它由常規文本和指令組成,它們控製每個參數必須放在格式化字符串中的位置和方式。
用法
string.format(“s = %a”)
上麵的 string.format() 語法包含一個標識符 s,它是字符串,標識符 a 是告訴如何格式化參數的字母。
有很多字母可以說明如何格式化參數,這些是 -
- ‘d’ - 十進製數
- ‘x’ - 十六進製
- ‘o’ - 八進製
- ‘f’ - 用於浮點數
- ‘s’ - 字符串
- 還有許多其他變體。
現在讓我們考慮一些示例,我們將在其中運行string.format()函數。
示例
考慮以下示例 -
s = string.format("x = %.4f",2345)
print(s)
輸出
x = 2345.0000
示例
現在讓我們再考慮一個例子,我們將以一種看起來與日期完全相似的格式打印字符串。考慮下麵顯示的示例 -
d = 5; m = 11; y = 2021
date = string.format("%02d/%02d/%04d",d,m,y)
print(date)
輸出
05/11/2021
相關用法
- Lua string.char()用法及代碼示例
- Lua string.gsub()用法及代碼示例
- Lua string.byte()用法及代碼示例
- Lua string.lower()用法及代碼示例
- Lua string.upper()用法及代碼示例
- Lua table.pack()用法及代碼示例
- Lua io.popen()用法及代碼示例
- Lua table.unpack()用法及代碼示例
- Lua math.modf()用法及代碼示例
- Lodash _.isValidDate()用法及代碼示例
- Lodash _.isInteger()用法及代碼示例
- Lodash _.sampleSize()用法及代碼示例
- Lodash _.fromQuery()用法及代碼示例
- Lodash _.noConflict()用法及代碼示例
- Lodash _.Intersection()用法及代碼示例
- Lodash _.values()用法及代碼示例
- Less isstring()用法及代碼示例
- Lodash _.isLength()用法及代碼示例
- Lodash _.third()用法及代碼示例
- Lodash _.negate()用法及代碼示例
注:本文由純淨天空篩選整理自Mukul Latiyan大神的英文原創作品 string.format() function in Lua programming。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。