【问题标题】:Return formatted string in Python在 Python 中返回格式化的字符串
【发布时间】:2015-10-26 17:32:41
【问题描述】:

我有一个字符串:

testString = """ My name is %s
and I am %s years old
and I live in %s"""

我有代码可以找到我想输入到 testString 的这三个字符串。我怎么做?在 Java 中我会这样做:

return String.format(testString, string1, string2, string3)

Python 中有没有等价物?

【问题讨论】:

  • 我在 Google 上搜索了“Python 字符串格式化”和“Python 格式化字符串”。在这两种情况下,相关文档都是第一个打击。你找到那个文档了吗?您在实施时遇到问题了吗?
  • @MartijnPieters 是的,我做到了,但遇到了问题。不过,由于给出的答案,它现在已修复。
  • @hokosha:然后分享该信息。总是分享你的研究。如果您遇到问题,我们可以帮助您解决该问题。
  • @MartijnPieters 好的,我明白了。问题是我需要返回那个字符串,就像我在 Java 示例中所做的那样。不过,我意识到我并没有真正澄清这一点。

标签: python string format


【解决方案1】:

这是使用%的版本:

print """ My name is %s
and I am %s years old
and I live in %s""" % ('tim', 6, 'new york')

这是我的首选版本:

testString = """ My name is {}
and I am {} years old
and I live in {}""".format(string1, string2, string3)

您可能想阅读https://docs.python.org/3.4/library/string.html#string-formatting

【讨论】:

  • Python 还支持%s 样式格式。我希望 OP 至少进行了足够的研究以找到相关文档。
  • 你是对的。我的偏好妨碍了……更新了。
  • @hiroprotagonist 我很确定你不能输入:“return testString % (string1, string2, string3)”,对吧?但是,您的首选版本有效。谢谢。
  • 实际上是的 - 你可以。
  • @hiroprotagonist 是的,我的错。我从“%s”更改为“{}”。这就是为什么。
猜你喜欢
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多