• python中的printf:%号拼接字符串和format函数


    在C语言中,我们使用printf("%s","hello")这种形式进行字符串的拼接

    在python中,进行这样的拼接有两种实现方式,分别是%号拼接以及使用format函数,以下进行代码演示

    %号拼接字符串


     在python中是用%号可以进行字符串的拼接,这个跟print函数是无关的。以下进行举例

    • 打印字符串
      msg = "i am %s,my blogs is %s" % ("CodeScrew","www.cnblogs.com/codescrew")
      print(msg)
    • 打印浮点数
      msg = "i am %0.2f m" %1.785
      print(msg)  #打印结果为i am 1.78 m

      其中%号后面的.2表示保留2位小数

    • 打印百分比
      msg = "it is %0.2f %%" % 99.852
      print(msg)  #打印结果为it is 99.85 %
    • 使用键值对进行拼接
      msg = "i am %(name)s.my age is %(age)d" % ({"name":"CodeScrew","age":23})
      print(msg)  #打印结果为i am CodeScrew.my age is 23

    format函数处理字符串


     除了%号进行拼接,还可以使用字符串类的format函数,以下列举了常用的使用。

    msg = "i am {},age is {}".format("CodeScrew",23)
    print(msg)  #打印结果为i am CodeScrew,age is 23
    
    msg = "i am {1},age is {0}".format("CodeScrew",23)
    print(msg)  #打印结果为i am 23,age is CodeScrew
    
    msg = "i am {name},age is {age}".format(name="CodeScrew",age=23)
    print(msg)  #打印结果为i am CodeScrew,age is 23
    
    msg = "i am {name},age is {age}".format(**{"name":"CodeScrew","age":23})
    print(msg)  #打印结果为i am CodeScrew,age is 23
    
    msg = "i am {:s},age is {:d}".format("CodeScrew",23)
    print(msg)  #打印结果为i am CodeScrew,age is 23
    
    msg = "i am {:s},age is {:d}".format(*["CodeScrew",23])
    print(msg)  #打印结果为i am CodeScrew,age is 23
    
    msg = "Numbers:{:b},{:o},{:d},{:x},{:X}".format(15,15,15,15,15)
    print(msg)  #打印结果为Numbers:1111,17,15,f,F
  • 相关阅读:
    51Nod-1013 3的幂的和【快速模幂+逆元】
    51Nod-1082 与7无关的数【进制+打表】
    51Nod-1080 两个数的平方和【暴力法】
    51Nod-1015 水仙花数【进制+查表搜索】
    51Nod-1003 阶乘后面0的数量【分析思维】
    51Nod-1002 数塔取数问题【DP】
    51Nod-1179 最大的最大公约数【暴力】
    51Nod-1018 排序【排序】
    51Nod-1126 求递推序列的第N项【递推序列+模除】
    51Nod-1031 骨牌覆盖【递推】
  • 原文地址:https://www.cnblogs.com/codescrew/p/8645902.html
Copyright © 2020-2023  润新知