码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-03-26 16:01:31      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:c语言   desc   实现   printf   .com   col   des   函数   两种   

在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

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

标签:c语言   desc   实现   printf   .com   col   des   函数   两种   

原文地址:https://www.cnblogs.com/codescrew/p/8645902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!