-2

I am learning Python on top of the Java, so I am having confusion in string concatenation functionality offered by Python. In Python, if you concatenate both string and number using simple plus(+) operator, it will throw you the error. However the same thing in Java prints the correct output and either concatenate the string and number or adds up them.

Why Python is not supporting the concatenation of both string and number in the same manner as Java.

  1. Is there any hidden advantage of that?
  2. How we can achieve the concatenation thing in Python

####################In Java########################33
System.out.println(10+15+"hello"+30) will give output 25hello30
System.out.println("hello"+10+15) will give output hello1015

#########In Python#########################
print(10+15+"hello"+30) will give error: unsupported operand type(s) for 
+: 'int' and 'str'
print("hello"+10+15) can ony concatenate str(not "int") to str
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
CRUZE
  • 57
  • 3
  • 11
  • 1
    Python just doesn't call `__str__` implicitly when concatenating values. Java [uses a StringBuilder object](https://stackoverflow.com/a/4262161/1540468) implicitly to avoid creating temporary strings. It will call the correct overload for each element and they will all be converted to strings. – Paul Rooney Jun 20 '19 at 03:48

2 Answers2

0

Java and Python are different languages. Java has a String concatenate that will "promote" an int to a String. In Python you have to do that yourself. Like,

print(str(10+15)+"hello"+str(30))
print("hello"+str(10)+str(15))

gives outputs:

>>> 25hello30
>>> hello1015
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    It is worth mentioning that the preferred way of string building in Python is the more extensible `.format()` method. – Selcuk Jun 20 '19 at 03:52
  • 1
    @Selcuk This is true, but so it is in Java with `System.out.printf("%dhello%d%n", 10+15, 30);` and `System.out.printf("hello%d%d%n", 10, 15)` – Elliott Frisch Jun 20 '19 at 04:07
0

1) Concatenating and adding two objects of a different type means guessing which type the result should be and how they should be combined, which is be why it is excluded in python. Languages make choices.

2) This question is already answered here. You can do something like this:

print("{}hello{}".format(10+15,30))
print("hello{}{}".format(10,15))

gives output:

>>> 25hello30
>>> hello1015