Python字串格式化

2021-08-20 17:49:29 字數 1246 閱讀 9415

本文介紹了python字串格式化,主要有兩種方法,分享給大家,具體如下

用於字串的拼接,效能更優。

字串格式化有兩種方式:百分號方式、format方式。

百分號方式比較老,而format方式是比較先進的,企圖替代古老的方式,目前兩者共存。

1、百分號方式

格式:%[(name)][flags][width].[precision]typecode

width    可選,占有寬度

.precision    可選,小數點後保留的位數

typecode     必選

>>> s = 'i am %s,age %d' %('cai',18)

>>> print(s)

i am cai,age 18

>>> s = 'i am %(n1)s,age %(n2)d' %

>>> print(s)

i am cai,age 18

>>> s = 'i am %(n1)+10s,age %(n2)d' %

>>> print(s)

i am cai,age 18

>>> s = 'i am %(n1)+10s,age %(n2)10d' %

>>> print(s)

i am cai,age 18

>>> s = "i am %.3f abcd" %1.2

>>> print(s)

i am 1.200 abcd

2、format方式

i1 = "i am {},age {} ,{}".format('cairui',18,'kk')

print(i1)

i am cairui,age 18 ,kk

i1 = "i am ,age ,".format('cairui',18)

print(i1)

i am cairui,age 18 ,cairui

i1 = "i am ,age ,".format(name='cairui',age=18)

print(i1)

i am cairui,age 18 ,cairui

i1 = "i am ,age ,".format('cairui',18,6.1)

print(i1)

i am cairui,age 18 ,6.100000

Python 字串格式化

字串格式化 s 格式化為字串 format hello,s.s enough for ya?values world hot print format values hello,world.hot enough for ya?f 格式化為實數 浮點數 format pi with three dec...

python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...

Python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...