格式化输出

一、字符串的格式化输出

1.类似于字符串的拼接,可用标点拼接

1)+

>>> st1 = 'LO'
>>> st2 = 'VE'
>>> st = st1 + st2
>>> st
'LOVE'

 2), 注:用逗号拼接之后变为元组

>>> st1 = 'LO'
>>> st2 = 'VE'
>>> st = st1,st2
>>> st
('LO', 'VE')

3)不添加任何字符

>>> st = 'LO''VE'
>>> st
'LOVE'
>>> 

 2. 在指定位置插入字符

1)%

Ⅰ. 插入字符用%s

①插入单个字符

>>> st1 = 'world'
>>> st = 'hello %s'%st1
>>> st
'hello world'

 ②插入多个字符

>>> st1 = ' '
>>> st2 = 'world'
>>> st3 = '!!'
>>> st = 'hello%s%s%s'%(st1,st2,st3)
>>> st
'hello world!!'

 ③控制长度,只需在%后边加上参数

>>> st = '123%3s'%123456
>>> st
'123123456'

 Ⅱ. 插入数字用%d

>>> st = '123%d'%1
>>> st
'1231'

 Ⅲ. 插入浮点数用%f

>>> st = '123%f'%3.14
>>> st
'1233.140000'

3. join

''.join(列表名)

举例:

>>> mylist = ['I','LOVE','YOU','!']
>>> st = ''.join(mylist)
>>> st
'ILOVEYOU!'
>>> st = ' '.join(mylist)
>>> st
'I LOVE YOU !'
>>> st = '***'.join(mylist)
>>> st
'I***LOVE***YOU***!'
>>> st = '---'.join(mylist)
>>> st
'I---LOVE---YOU---!'

4. format

1)与%类似,占位符用{},后缀为format(str1,str2)

>>> st = 'name:{} age:{} sex:{}'.format('SuXin','18','man')
>>> st
'name:SuXin age:18 sex:man'
>>> st = 'name:{2} age:{1} sex:{0}'.format('SuXin','18','man')
>>> st
'name:man age:18 sex:SuXin'

2) 指定属性插入

在{}中写入要插入的属性,后缀采用“属性=值”的形式

>>> st = 'name:{name}  age:{age}  sex:{sex}'.format(name='SuXin',age=18,sex='Man')
>>> st
'name:SuXin  age:18  sex:Man'

补位

<字符在左边   >字符在右边   ^字符在中间

>>> '{a:*<30}'.format(a='SuXin')
'SuXin*************************'
>>> '{a:*>30}'.format(a='SuXin')
'*************************SuXin'
>>> '{a:*^30}'.format(a='SuXin')
'************SuXin*************'

 3)传入变量

基本流程:将该整合的字符串赋值给一个变量,然后变量名加要添加的字符即可实现

>>> st = 'Number: {}'.format
>>> st(1)
'Number: 1'
>>> st('One')
'Number: One'

 

你可能感兴趣的:(格式化输出)