博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python字符串| 带示例的format()方法
阅读量:2529 次
发布时间:2019-05-11

本文共 2162 字,大约阅读时间需要 7 分钟。

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 nameprint "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 variablesname = "Amit"age = 21print "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 = 10b = 20sum = a+b# output 1print "sum = {0}".format (sum)# output 2print "Sum of {0} and {1} is = {2}".format (a, b, sum)# finding average and printing a = 11b = 20sub = a+bprint "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

翻译自:

转载地址:http://prxzd.baihongyu.com/

你可能感兴趣的文章
详解C# 匿名对象(匿名类型)、var、动态类型 dynamic
查看>>
centos7 开放端口
查看>>
迷宫实现
查看>>
如何使用Transact-SQL进行事务处理[示例]
查看>>
选择JSF不选Struts的十大理由
查看>>
01-编写CMS注意事项
查看>>
SQL 事务
查看>>
element的form表单中如何一行显示多el-form-item标签
查看>>
SQL Server两种分页的存储过程介绍
查看>>
09 audio和vedio标签
查看>>
【HDU 6299】Balanced Sequence
查看>>
【】minimum
查看>>
【CS Round #46 (Div. 1.5) B】Letters Deque
查看>>
自制常用工具类Common
查看>>
hdoj 4940 强连通图
查看>>
Shell脚本编写
查看>>
Spark系列(三)SparkContext分析
查看>>
UnityWebReqest和WWW,请求web数据打包到Android手机上,报错 Unknown error记录
查看>>
Java字符串首字母大写
查看>>
一个前端博客(7)——事件绑定和移除事件
查看>>