日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2023/12/1 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python字符串| 带示例的format()方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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()方法用于格式化字符串(換句話說,我們可以說實(shí)現(xiàn)了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.

當(dāng)需要在字符串中顯示變量的值時(shí),可以通過將{}放在要放置值的位置來設(shè)置其格式。 {}是一個(gè)替換字段,它用format()方法中的給定值替換。

The field {} contains the index to replace, the value specified in the format function.

字段{}包含要替換的索引,即格式函數(shù)中指定的值。

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.

讓假設(shè),存在用于對(duì)所述第三值的第二值和{2}等將被使用的格式方法中指定三個(gè)值,{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是參數(shù)的索引。

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 = 21print "My name is {0}, I am {1} years old".format (name,age)

Output

輸出量

My name is AmitMy name is Amit, I am 21 years oldMy name is Amit, I am 21 years old

Example program 2: (Calculating SUM, AVERAGE, and printing in different output formats)

示例程序2 :(計(jì)算SUM,AVERAGE和以不同的輸出格式進(jìn)行打印)

a = 10 b = 20sum = 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 = 20sub = a+bprint "Average of {0} and {1} is = {2}".format (a, b, float(sum)/2)

Output

輸出量

sum = 30Sum of 10 and 20 is = 30Average of 11 and 20 is = 15.0

翻譯自: https://www.includehelp.com/python/string-format-method-with-example.aspx

總結(jié)

以上是生活随笔為你收集整理的Python字符串| 带示例的format()方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。