关闭

3.7.7 - String Formatting

168人阅读 评论(0) 收藏 举报
分类:
a = 1
b = 2
c = 4.32456

#Use the format method to replace {0} with the sum of a + b

"The sum of a + b is {0}".format(a + b)

"a: {0}  b: {1} c: {2}".format(a, b, c)

"a: " + str(a) + " b: " + str(b) + " c: " + str(c)

"a:{0:04d}".format(a)

"c: {0:0.2f}".format(c)


"The sum of a + b is %s" % ( a + b)

"c: %0.2f" % (c)

 


运行结果如下:

"The sum of a + b is {0}".format(a + b)

// Result: The sum of a + b is 3 //

"a: {0} b: {1} c: {2}".format(a, b, c)

// Result: a: 1 b: 2 c: 4.32456 //

"a: " + str(a) + " b: " + str(b) + " c: " + str(c)

// Result: a: 1 b: 2 c: 4.32456 //

"a:{0:04d}".format(a)

// Result: a:0001 //

"c: {0:0.2f}".format(c)

// Result: c: 4.32 //

"The sum of a + b is %s" % ( a + b)

// Result: The sum of a + b is 3 //

"c: %0.2f" % (c)

// Result: c: 4.32 //


%()  类似.format()


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:473947次
    • 积分:10853
    • 等级:
    • 排名:第1679名
    • 原创:610篇
    • 转载:98篇
    • 译文:0篇
    • 评论:97条
    文章分类
    最新评论