String.format()方法 (String.format() Method)
format() method is used to format the string (in other words - we can say to achieve the functionality like printf() in C language).
format()方法用于格式化字符串(换句话说,我们可以说实现了C语言中类似于printf()的功能)。
When we need to display the values of the variables inside the string, we can format it by placing {} where we want to place the value. {} is a replacement field, that replaces with the given value in format() method.
当需要在字符串中显示变量的值时,可以通过将{}放在要放置值的位置来设置其格式。 {}是一个替换字段,它用format()方法中的给定值替换。
The field {} contains the index to replace, the value specified in the format function.
字段{}包含要替换的索引,即格式函数中指定的值。
Let suppose, there are three values specified in the format method, {0} for the first value, {1} for the second value and {2} for the third value and so on will be used.
让假设,存在用于对所述第三值的第二值和{2}等将被使用的格式方法中指定三个值,{0}为所述第一值,{1}。
Syntax:
句法:
String.format(parameter1, parameter2,...)
Here, parameter1, parameter2, ... are the values/variables that will print within the string by replacing the field {N}. Where N is the index of the parameter.
在这里, parameter1,parameter2,...是通过替换字段{N}将在字符串中打印的值/变量。 其中N是参数的索引。
Example:
例:
print "{0}, {1} and {2}".format("ABC", "PQR", "XYZ")
This statement will print "ABC, PQR, and XYZ"
Example program 1: (printing name, age in different output formats)
示例程序1 :(打印名称,使用不同输出格式的年龄)
# printing name
print "My name is {0}".format("Amit")
# printing name and age
print "My name is {0}, I am {1} years old".format ("Amit", 21)
# printing name and age through variables
name = "Amit"
age = 21
print "My name is {0}, I am {1} years old".format (name,age)
Output
输出量
My name is Amit
My name is Amit, I am 21 years old
My name is Amit, I am 21 years old
Example program 2: (Calculating SUM, AVERAGE, and printing in different output formats)
示例程序2 :(计算SUM,AVERAGE和以不同的输出格式进行打印)
a = 10
b = 20
sum = a+b
# output 1
print "sum = {0}".format (sum)
# output 2
print "Sum of {0} and {1} is = {2}".format (a, b, sum)
# finding average and printing
a = 11
b = 20
sub = a+b
print "Average of {0} and {1} is = {2}".format (a, b, float(sum)/2)
Output
输出量
sum = 30
Sum of 10 and 20 is = 30
Average of 11 and 20 is = 15.0
翻译自: https://www.includehelp.com/python/string-format-method-with-example.aspx