python 字串格式化

2021-09-10 06:49:49 字數 1760 閱讀 9731

msg = 'i am %s my hobby is alex' %'ly'

print(msg)

msg = 'i am %s my hobby is alex %s' %('ly','haha')

print(msg)

msg = 'i am %s my hobby is alex %s' % ('ly',[1,2])

print(msg)

msg = 'i am %d my hobby is alex' %1

print(msg)

msg = 'i am %s my hobby is alex %d' % ('ly',1)

print(msg)

name = 'ly'

age = 19

msg = 'i am %s my hobby is alex %d' % (name,age)

print(msg)

#列印浮點數

tpl = "percent %.f" % 99.346655446434465656646

print(tpl)

tpl = "percent %.2f" % 99.346655446434465656646

print(tpl)

#擷取邪門歪道

tpl = "percent %.2s" % 99.23543543565476723

print(tpl)

tpl = "percent %.4s" % 99.23543543565476723

print(tpl)

#列印百分比

tpl = "percent %.2f %%" % 99.234325246446425642643632

print(tpl)

#傳入鍵值

tpl = "i am %(name)s age %(age)d" %

print(tpl)

msg = 'i am %(name)-60s my hobby is alex' %

print(msg)

#拼接print('root','x','0','0',sep=':')

############################### format字串格式化 ###############################

tpl = "i am {},age {},{}".format("seven",18,'alex')

print(tpl)

tpl = "i am ,age ,".format("seven",18,'alex')

print(tpl)

tpl = "i am ,age ,".format("seven")

print(tpl)

tpl = "i am ,age ,really ".format(name="seven",age=18)

print(tpl)

tpl = "i am ,age ".format(**) # ** 代表把字典的鍵值對取出來

print(tpl)

#l = ["seven", 18]

tpl = "i am , age ".format(*l) # *號的作用是把列表裡的元素遍歷一遍

print(tpl)

# b二進位制 o八進位制 d整形 x16進製制 x16進製制 %列印百分比

tpl = "number: ,,,,,".format(15, 15, 15, 15, 15, 15.34562, 2)

print(tpl)

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中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...