Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串格式-旧的“%”与新的“str.format”`_Python_String_Python 2.7_String Formatting - Fatal编程技术网

Python字符串格式-旧的“%”与新的“str.format”`

Python字符串格式-旧的“%”与新的“str.format”`,python,string,python-2.7,string-formatting,Python,String,Python 2.7,String Formatting,新格式允许我们这样做:“{:。要使用新格式执行可变长度,可以使用替换的嵌套- >>> '{:{}<{}}'.format('##','.',12) '##..........' >>> '{:{}<{}}'.format('##','-',12) '##----------' >>> '{:{}<{}}'.format('##','-',20) '##------------------' >>'{:{}使用格式可以嵌套替

新格式允许我们这样做:
“{:。要使用新格式执行可变长度,可以使用替换的嵌套-

>>> '{:{}<{}}'.format('##','.',12)
'##..........'
>>> '{:{}<{}}'.format('##','-',12)
'##----------'
>>> '{:{}<{}}'.format('##','-',20)
'##------------------'

>>'{:{}使用
格式
可以嵌套替换:

'{:.<{}}'.format('##',12)

“{:。对于问题的第一部分,您可以左对齐并使用一个空格作为填充字符,宽度为12:


“%-*s”“(12),###”)
可以替换为
”{:嗯,想听听我的答案有什么错。第一部分的想法是使用可变长度。嵌套格式解决了这个问题。感谢链接!没问题,然后嵌套
{}
就可以了
{:
>>> '{: <12}'.format('##')
'##          '
>>> '{2:{0}<{1}}'.format('.',12,'##')
'##..........'
>>> '{0:{1}<{2}}'.format('##','-',20)
'##------------------'
'{:.<{}}'.format('##',12)
Align right:

Old '%10s' % ('test',) 
New '{:>10}'.format('test')

Align left:

Old

'%-10s' % ('test',)
New

'{:10}'.format('test')
Old

'%*s' % ((- 8), 'test')
New

'{:<{}s}'.format('test', 8)
New

'{:_<10}'.format('test')
Output
New

'{:^10}'.format('test')