Reputation: 3621
I would like to concatenate strings and variable values in Python 3.
For instance, in R
I can do the following:
today <- as.character(Sys.Date())
paste0("In ", substr(today,1,4), " this can be an R way")
Executing this code in R
yields [1] "In the year 2018 R is so straightforward"
.
In Python 3.6
have tried things like:
today = datetime.datetime.now()
"In year " + today.year + " I should learn more Python"
today.year
on its own yields 2018
, but the whole concatenation yields the error: 'int' object is not callable
What's the best way to concatenate strings and variable values in Python3?
Upvotes: 6
Views: 22343
Reputation: 886938
If we need to use .
way then str()
is equivalent to __str__()
>>> "In year " + today.year.__str__() + " I should learn more Python"
# 'In year 2018 I should learn more Python'
Upvotes: 1
Reputation: 98
You could try to convert today.year into a string using str().
It would be something like that:
"In year " + str(today.year) + " I should learn more Python"
Upvotes: 6