【问题标题】:String Formatting Easiest Prettiest [duplicate]字符串格式最简单最漂亮[重复]
【发布时间】:2014-08-24 21:45:51
【问题描述】:

我发现用我当前使用的语法格式化一个字符串需要花费很多时间和精力:

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

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

【问题讨论】:

  • 您的意思是您的打字流程被打断了?
  • 这不是重复的。格式只是处理字符串的众多可能方法之一。连接等其他选项是此问题的一个选项。或者可能基于string.join

标签: python string string-formatting


【解决方案1】:

您可能正在寻找 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 来简单地unpack myList 而不是(myList[1],myList[0],myList[2])。然后,通过对格式字段进行编号,您可以将子字符串按您想要的顺序排列。

还要注意,如果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.'
>>>

【讨论】:

  • 使用str.format,如果需要,您还可以在格式字符串中进行索引而不是解包:"The number {0[1]} is larger than {0[0]} but smaller than {0[2]}.".format(mylist)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多