zoukankan      html  css  js  c++  java
  • [ Skill ] print println printf fprintf sprintf lsprintf

    https://www.cnblogs.com/yeungchie/

    几种 print 函数的差异

    print

    • 接收任意的数据类型,并打印到 CIW
    print( 12345 )        ; 12345
    print( "YEUNGCHIE" )  ; "YEUNGCHIE"
    print( winId )        ; window:1
    print( cvId )         ; db:0x21e4c01a
    
    • 第二参数可选指定 IO 句柄
    print( "String" port )
    
    • 返回值恒为 nil

    println

    • print 区别在于 println 打印一个数据后会自动换行

    举个例子,同时运行 3 个 print

    print( 1 ) print( 2 ) print( 3 )
    ; 123
    

    同时运行 3 个 println

    println( 1 ) println( 2 ) println( 3 )
    ; 1
    ; 2
    ; 3
    

    printf

    • 格式化输出字符串
    • 第一个参数定义输出字符串格式 format,例如下面能够识别其中的 转义符(\) 和 字符串占位符(%s)
    • 从第二个参数开始会依次替换 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"
    
  • 相关阅读:
    NET(C#)接入Dubbo服务,Zookeeper作为Dubbo服务的注册中心,实现thrift协议访问接口(3)
    zend studio快捷键
    Guid的生成和数据修整(去除空格和小写字符)
    工作中常用Windows快捷键整理(1)-快速关闭网页
    PHP学习笔记(3)-Zend Studio安装和汉化
    PHP学习笔记(2)
    PHP学习笔记(1)
    判断本机ip是电信还是网通
    作业 4/1
    logging 模块
  • 原文地址:https://www.cnblogs.com/yeungchie/p/15758985.html
Copyright © 2011-2022 走看看