zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    springCloud学习6(Spring Cloud Sleuth 分布式跟踪)
    springCloud学习5(Spring-Cloud-Stream事件驱动)
    springCloud学习4(Zuul服务路由)
    springCloud学习3(Netflix Hystrix弹性客户端)
    springCloud学习笔记2(服务发现)
    EFCore
    webBrowser.DocumentText重新赋值无效解决方法
    C# SQLite写入和读取DateTime类型
    自定义协议链接 ------2.实践篇
    自定义协议链接 ------1.原理篇
  • 原文地址:https://www.cnblogs.com/codescrew/p/8645902.html
Copyright © 2011-2022 走看看