Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 654
user3507584 Avatar asked Jan 14 '18 19:01

user3507584


People also ask

How do you concatenate a string and a variable?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate strings and numbers?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

How do you concatenate strings and variables in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.


2 Answers

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"
like image 116
Cássio Salvador Avatar answered Sep 30 '22 10:09

Cássio Salvador


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'
like image 40
akrun Avatar answered Sep 30 '22 08:09

akrun