python格式化输出:% 和.format

在python的使用过程中难免会遇到类似下面的情况:

result = 0.1
iteration = 1000
print("result after iteration: %d: %f" %(iteration,result))

result after iteration: 1000: 0.100000

输出字符串时经常需要用到占位符%
1.常用占位符类型:
%s:字符串
%d或%i:十进制整数
%f:浮点数

2.使用方法
在输出字符串时,根据需要在我们希望插入变量或字符串的位置加上占位符%,并指定其类型,如:%d,%s等;在字符串结尾的“后面插入%,并在其后加入对应的变量值或字符串。
文字说明可能不清晰,代码更直观一些:

print("hello %s" % 'world')       #只有一个%时,()可以省略
hello world

print("%s %s" %('hello','world'))
hello world

age = 23
name = 'Alice'
print("%s is %d years old." %(name,age))    #变量不需要加''

Alice is 23 years old.

3.强大的format

print("hello {}".format("world"))
hello world

print("{0} {1}".format("hello","world"))
hello world

print("{1} {2}{0}".format("!","hello","world"))
hello world!

a = 'hello'
b = 'world'
print("{0} {1}".format(a,b))
hello world

注:{}中的数字表示format()中的位置

个人原创,转载请注明原文出处!(如果文章对您有帮助,请点点赞支持一下作者呀!)

发布了12 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxdd2018/article/details/89186357