【问题标题】:concatenation of triple quoted strings三重引号字符串的连接
【发布时间】:2014-06-05 21:53:54
【问题描述】:

我目前正在尝试使用变量在三引号字符串中进行连接。解决这个问题的最佳方法是什么?

print('''
Points left to spend: ''' + str(pointsLeft) + '''
''' + str(attrChoice) + ':\t' + '''[''' + str(charAttr[attrChoice]) + ''']
To reduce the number of points spent on this skill, simply enter a negative number.
'''
)

我得到的错误信息是:关键字不能是表达式。谁能解释这意味着什么以及是否有可能尝试这种连接?

【问题讨论】:

  • attrChoicecharAttr 等是什么?

标签: python syntax-error concatenation string-interpolation


【解决方案1】:

最好的方法是使用str.format

template = """This is a 
multiline {0} with
replacement {1} in."""

print(template.format("string", "fields"))

从 Python 3.6(参见 PEP 498)开始,您可以使用“f-string”执行此操作,如下所示:

print(f'''
Points left to spend: {pointsLeft}
{attrChoice}:\t[{charAttr[attrChoice]}]
To reduce the number of points spent on this skill, simply enter a negative number.
'''
)

【讨论】:

  • 谢谢。那应该是有效的。我会标记你,但缺乏声誉。
  • @PedroRhian 如果答案解决了您的问题,您可以接受 - 请参阅stackoverflow.com/help/someone-answers
  • 如何在同一个字符串中进行多次替换?
  • @PedroRhian 你是什么意思?我的示例有多个替换。
  • 我发现这个解决方案在创建 HTML 或 XML 文档时特别有用。
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多