连接字符串和变量值
Concatenate strings and variable values
我想在 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 中连接字符串和变量值的最佳方法是什么?
您可以尝试使用 str() 将 today.year 转换为字符串。
会是这样的:
"In year " + str(today.year) + " I should learn more Python"
如果我们需要使用.
方式那么str()
等同于__str__()
>>> "In year " + today.year.__str__() + " I should learn more Python"
# 'In year 2018 I should learn more Python'
我想在 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 中连接字符串和变量值的最佳方法是什么?
您可以尝试使用 str() 将 today.year 转换为字符串。
会是这样的:
"In year " + str(today.year) + " I should learn more Python"
如果我们需要使用.
方式那么str()
等同于__str__()
>>> "In year " + today.year.__str__() + " I should learn more Python"
# 'In year 2018 I should learn more Python'