Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation without '+' operator

I was playing with python and I realized we don't need to use '+' operator to concatenate static strings. But it fails if I assign it to a variable.

For example:

string1 = 'Hello'   'World'  #1 works fine string2 = 'Hello' + 'World'  #2 also works fine  string3 = 'Hello' string4 = 'World' string5 = string3   string4  #3 causes syntax error string6 = string3 + string4  #4 works fine 

Now I have two questions:

  1. Why statement 3 does not work while statement 1 does?
  2. Is there any technical difference such as calculation speed etc. between statement 1 and 2?
like image 979
ibrahim Avatar asked Sep 17 '13 06:09

ibrahim


People also ask

How do you add two strings without an operator?

You can use str. join(list_of_strings) from the string class. The string you call it on is used to join the list of strings you provide as argument to it.

How do you concatenate a string in Python without?

There are two ways to concatenate string literals in Python: Using the + operator between two string literals. This also works for variables. Using adjancent string literals without the + operator.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

Can you use += for string concatenation?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .


1 Answers

From the docs:

Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".


Statement 3 doesn't work because:

The ‘+’ operator must be used to concatenate string expressions at run time.

Notice that the title of the subheader in the docs is "string literal concatenation" too. This only works for string literals, not other objects.


There's probably no difference. If there is, it's probably extremely tiny and nothing that anyone should worry about.


Also, understand that there can be dangers to this:

>>> def foo(bar, baz=None): ...     return bar ...  >>> foo("bob" ... "bill") 'bobbill' 

This is a perfect example of where Errors should never pass silently. What if I wanted "bill" to be the argument baz? I have forgotton a comma, but no error is raised. Instead, concatenation has taken place.

like image 118
TerryA Avatar answered Oct 09 '22 09:10

TerryA