【问题标题】:Python string formatting with percent sign带百分号的 Python 字符串格式
【发布时间】:2015-11-05 01:05:51
【问题描述】:

我正在尝试执行以下操作:

>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'

不过,我有一个很长的x,不止两个,所以我试了一下:

>>> '%d,%d,%s' % (*x, y)

但这是语法错误。没有像第一个示例那样索引的正确方法是什么?

【问题讨论】:

  • Pythonic 方式是使用str.format
  • 它是否更“pythonic”是有争议的,但str.format 允许您使用*args 扩展,因为它是一个方法调用

标签: python string python-3.x string-formatting


【解决方案1】:

也许看看str.format()

>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'

更新:

为了完整起见,我还包括PEP 448 描述的其他解包概括Python 3.5中引入了扩展语法,以下不再是语法错误:

>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {}'
>>> template.format(*x, y)  # valid in Python3.5+
'first: 5, second: 7, last: 42'

然而,在 Python 3.4 及更低版本 中,如果您想在解压后的元组之后传递其他参数,最好将它们作为命名参数传递

>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {last}'
>>> template.format(*x, last=y)
'first: 5, second: 7, last: 42'

这避免了构建一个在末尾包含一个额外元素的新元组的需要。

【讨论】:

  • 这属于评论,而不是作为答案,除非您对其进行扩展并展示如何使用 str.format() 来执行 OP 尝试执行的操作。
  • 是的,正在写,但意外地太快发布了答案。
  • 如何在我之前的例子中采用这个? '{},{},{}'.format( *x,y ) 还是不行?
  • '{1},{2},{0}'.format(y, *x ) - 位置参数扩展运算符必须在所有其他位置参数之后 - 但您可以使用技巧并在模板中标记占位符来更改顺序。
  • @plamut 请注意,PEP 448 会更改并允许 .format(*x, y)
【解决方案2】:

str % .. 接受元组作为右手操作数,因此您可以执行以下操作:

>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,))  # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'

您的尝试应该在 Python 3 中工作。其中支持 Additional Unpacking Generalizations,但在 Python 2.x 中不支持:

>>> '%d,%d,%s' % (*x, y)
'1,2,hello'

【讨论】:

  • 实际上扩展的可迭代解包确实不允许允许该语法(python3.4):>>> '%d,%d,%s' % (*x, y) File "<stdin>", line 1 SyntaxError: can use starred expression only as assignment target 也许python3.5的Additional Unpacking Generalizations允许它
  • @Bakuriu,感谢您指出这一点。我相应地更新了答案。
【解决方案3】:

我建议您使用str.format 而不是str %,因为它“更现代”并且具有更好的功能集。那就是说你想要的是:

>>> x = (1,2)
>>> y = 'hello'
>>> '{},{},{}'.format(*(x + (y,)))
1,2,hello

有关format 的所有酷炫功能(以及一些与% 相关的功能),请查看PyFormat

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 2015-11-13
    • 2020-05-11
    • 2019-01-14
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多