Python字符串| 带示例的format()方法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值