我发现它需要相当多的关注,时间是用我目前正在使用的语法格式化字符串的时间:
myList=['one','two','three']
myString='The number %s is larger than %s but smaller than %s.'%(myList[1],myList[0],myList[2])
结果:
"The number two is larger than one but smaller than three"
很奇怪,但每当我到达%
键盘键后跟s
时,我觉得有点被打断......
我想知道是否有其他方法可以实现类似的字符串格式化。请发一些例子。
答案 0 :(得分:4)
您可能正在寻找str.format
,这是执行字符串格式化操作的新方法:
>>> myList=['one','two','three']
>>> 'The number {1} is larger than {0} but smaller than {2}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>
此方法的主要优点是,您可以通过执行(myList[1],myList[0],myList[2])
而不是myList
,而只需unpack *myList
。然后,通过对格式字段进行编号,您可以按所需顺序放置子字符串。
另请注意,如果myList
已按顺序排列,则无需对格式字段进行编号:
>>> myList=['two','one','three']
>>> 'The number {} is larger than {} but smaller than {}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>