[ Skill ] print println printf fprintf sprintf lsprintf
作者:互联网
https://www.cnblogs.com/yeungchie/
几种 print 函数的差异
- 接收任意的数据类型
print( 12345 ) ; 12345
print( "YEUNGCHIE" ) ; "YEUNGCHIE"
print( winId ) ; window:1
print( cvId ) ; db:0x21e4c01a
- 第二参数可选指定 IO 句柄
print( "String" port )
- 返回值恒为
nil
println
- 与
print
区别在于会自动在末尾加上换行符\n
举个例子,同时运行 3 个 print
print( 1 ) print( 2 ) print( 3 )
; 123
同时运行 3 个 println
println( 1 ) println( 2 ) println( 3 )
; 1
; 2
; 3
printf
- 格式化输出字符串
- 第一个参数定义输出字符串格式 format,可以内插
%
格式化字符 - 从第二个参数开始会依次替换 format 中定义的
%
who = "YEUNGCHIE"
printf( "My name is %s and weight is %d kg\n" who 999 )
; My name is YEUNGCHIE and weight is 999 kg
- 输出成功,返回
t
,输出不成功都是报 error。
更详细的使用方法可以看以前的这篇随笔 [ Skill ] 中的通用输出格式规范
fprintf
- 与
printf
的区别是,用来输出到 IO 句柄(可以用来输出到文件)
file = outfile( "~/text.txt" )
fprintf( file "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
close(file)
- 将会生成一个文件
~/text.txt
> cat ~/text.txt
My name is YEUNGCHIE and weight is 999 kg
- 成功输出到文件即返回
t
sprintf
- 与
fprintf
的区别是,用来输出到变量
sprintf( variable "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
variable = sprintf( nil "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
; "My name is YEUNGCHIE and weight is 999 kg"
上面两句的效果是一样的,
variable
将会被赋值为格式化后的字符串。
- 成功格式化即返回字符串内容
lsprintf
- 与
sprintf
的区别是,第一个参数不用于指定被赋值的变量。
string = lsprintf( "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
- 成功格式化即返回字符串内容
- 当输出的参数数量不确定的时候这个函数非常好用,举个例子:
format = "My name is %s and weight is %d kg\n"
args = list( "YEUNGCHIE" 999 )
string = apply( 'lsprintf format args )
; "My name is YEUNGCHIE and weight is 999 kg"
- 当然
sprintf
也不是做不到,只不过会比较麻烦。
string = apply(
lambda(( a \@rest b )
apply( 'sprintf nil a b )
)
format
args
)
; "My name is YEUNGCHIE and weight is 999 kg"
标签:name,lsprintf,999,YEUNGCHIE,weight,print,fprintf,println,My 来源: https://www.cnblogs.com/yeungchie/p/15758985.html