Python 字符串格式最简单最漂亮

Python 字符串格式最简单最漂亮,python,string,string-formatting,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时,我都会觉得有

我发现用我目前使用的语法格式化字符串需要相当多的精力、时间和精力:

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

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

您可能正在寻找执行字符串格式化操作的新的首选方法:

>>> 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
即可执行
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.'
>>>

你是说你的打字流程中断了?这不是重复的。格式化只是处理字符串的许多可能方法之一。其他选项(如连接)也是这个问题的选项。或者是基于
string.join
str.format
的一些东西,如果您愿意,
“数字{0[1]}大于{0[0]},但小于{0[2]}。”.format(mylist)