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

时间:2023-03-08 23:45:29
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