6

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?

4
  • do you know how to use sprintf in R? the same can be accomplished in python by applying the % operator to a string. you can also .format a string. Commented Jan 14, 2018 at 19:55
  • 3
    Try "In year " + str(today.year) + " I should learn more Python". Commented Jan 14, 2018 at 19:55
  • The other commenters/answerers are giving you alternative approaches, but I think your code may have another issue. Rather than an error that says 'int' object is not callable', I would expect a TypeError saying cannot concatenate 'str' and 'int' objects. Commented Jan 14, 2018 at 19:59
  • @nicola This worked fine and as expected. Commented Jan 14, 2018 at 20:02

2 Answers 2

6

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.