【发布时间】: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'的错误,我希望TypeError说cannot concatenate 'str' and 'int' objects。 -
@nicola 这工作正常,符合预期。
标签: python r concatenation string-concatenation