User981636
User981636

Reputation: 3621

Concatenate strings and variable values

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

Answers (2)

akrun
akrun

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

C&#225;ssio Salvador
C&#225;ssio Salvador

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

Related Questions