gpt4 book ai didi

python - 连接字符串和变量值

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:37 25 4
gpt4 key购买 nike

我想在 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"

关于python - 连接字符串和变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48253554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com