字符串格式最简单最漂亮

时间:2014-07-03 16:46:53

标签: python string string-formatting

我发现它需要相当多的关注,时间是用我目前正在使用的语法格式化字符串的时间:

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时,我觉得有点被打断......

我想知道是否有其他方法可以实现类似的字符串格式化。请发一些例子。

1 个答案:

答案 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.'
>>>