Python中字符串的Format用法。

一、例子:

"_".join(["1","2","3","4"])
"_".join(map(lambda x:str(x),[1,2,3,4]))
"{0}-{1}".format(3.4,34)
"{}-{}-{}".format(3,4,5)
"{name}-{age}".format(**{'name':'song','age':34})
"{name}-{age}".format(name='song',age=34)
"the list first is: {obj[0]}".format(obj=[1,2,3,4])
"the list first is: {0[0]},{0[1]}".format([1,2,3,4])
"{:>8}".format('abc')
"{0:<8}".format('abc')
"{0:_<8}".format('abc')
"{0:0>8}".format('3.14')
"{0:.2f}".format(123.123456)
"{0:b}".format(1023)
"{0:d}".format(0b1111111111)
"{0:x}".format(1023)
"{0:,}".format(102345.6789)

二、结果:

>>> "_".join(["1","2","3","4"])
'1_2_3_4'
>>> "_".join(map(lambda x:str(x),[1,2,3,4]))
'1_2_3_4'
>>> "{0}-{1}".format(3.4,34)
'3.4-34'
>>> "{}-{}-{}".format(3,4,5)
'3-4-5'
>>> "{name}-{age}".format(**{'name':'song','age':34})
'song-34'
>>> "{name}-{age}".format(name='song',age=34)
'song-34'
>>> "the list first is: {obj[0]}".format(obj=[1,2,3,4])
'the list first is: 1'
>>> "the list first is: {0[0]},{0[1]}".format([1,2,3,4])
'the list first is: 1,2'
>>> "{:>8}".format('abc')
'     abc'
>>> "{0:<8}".format('abc')
'abc     '
>>> "{0:_<8}".format('abc')
'abc_____'
>>> "{0:0>8}".format('3.14')
'00003.14'
>>> "{0:.2f}".format(123.123456)
'123.12'
>>> "{0:b}".format(1023)
'1111111111'
>>> "{0:d}".format(0b1111111111)
'1023'
>>> "{0:x}".format(1023)
'3ff'
>>> "{0:,}".format(102345.6789)
'102,345.6789'
>>> 
原文地址:https://www.cnblogs.com/songxingzhu/p/7056847.html