【问题标题】:Concatenate strings and variable values连接字符串和变量值
【发布时间】:2018-06-23 12:38:53
【问题描述】:

我想在 Python 3 中连接字符串和变量值。 例如,在R 中,我可以执行以下操作:

today <- as.character(Sys.Date())
paste0("In ", substr(today,1,4), " this can be an R way") 

R 中执行此代码会产生[1] "In the year 2018 R is so straightforward"

Python 3.6 尝试过类似的事情:

today = datetime.datetime.now()
"In year " + today.year + " I should learn more Python"

today.year 自身产生 2018,但整个串联产生错误:'int' object is not callable

在 Python3 中连接字符串和变量值的最佳方法是什么?

【问题讨论】:

  • 你知道如何在R中使用sprintf吗?通过将 % 运算符应用于字符串,可以在 python 中完成相同的操作。你也可以.format一个字符串。
  • 试试"In year " + str(today.year) + " I should learn more Python"
  • 其他评论者/回答者正在为您提供替代方法,但我认为您的代码可能还有另一个问题。而不是说'int' object is not callable'的错误,我希望TypeErrorcannot concatenate 'str' and 'int' objects
  • @nicola 这工作正常,符合预期。

标签: python r concatenation string-concatenation


【解决方案1】:

您可以尝试使用 str() 将 today.year 转换为字符串。

应该是这样的:

"In year " + str(today.year) + " I should learn more Python"

【讨论】:

    【解决方案2】:

    如果我们需要使用.的方式那么str()就相当于__str__()

    >>> "In year " + today.year.__str__() + " I should learn more Python"
    # 'In year 2018 I should learn more Python'
    

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多