连接字符串和变量值

时间:2018-01-14 19:53:00

标签: python r concatenation string-concatenation

我想在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中连接字符串和变量值的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

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

会是这样的:

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

答案 1 :(得分:1)

如果我们需要使用.方式,则str()相当于__str__()

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