Is there any way to add one string to the end of another in python? e.g.
String1 = 'A' String2 = 'B'
and i want String3 == 'AB'
Is there any way to add one string to the end of another in python? e.g.
String1 = 'A' String2 = 'B'
and i want String3 == 'AB'
String concatenation in python is straightforward
a = "A"
b = "B"
c = a + b
print c
> AB
I benchmarked the three operations, performing 1m of each:
c = a + b
c = '%s%s' % (a,b)
c = "{0}{1}".format(a, b)
And the results are:
+: 0.232225275772
%s: 0.42436670365
{}: 0.683854960343
Even with 500 character strings, + is still fastest by far. My script is on ideone and the results (for 500 char strings) are:
+: 0.82
%s: 1.54
{}: 2.03
You could use the simplest version: String3 = String1 + String2
or the format operator (deprecated in python3): String3 = '%s%s' % (String1, String2)
In Python, the + operator concatenates strings:
>>> String3 = String1 + String2
>>> String3
'AB'
This is the simplest way and usually it's the right choice. However, sometimes you might need a more efficient string concatenation.
For simplicity when speed doesn't matter, you can't beat the ease of c=a+b
. If speed does matter (because you're making a large number of successive concatenations, for example), str.join()
can be a little more efficient (code at ideone).
+: 2.51
''.join([a,...z]): 0.2
append(): 2.05
From what I can tell, if you are making successive concatenations without touching the intermediate product, I'm better off appending each addition to a list, then joining everything at once. For the single concatenation case, a+b
is still faster than a.join(b)
You can also try out str.join():
>>>s1='a'
>>>s2='b'
>>>s3=''.join((s1,s2))
>>>s3
'ab'
also if you write:
>>>s3='WhatEver'.join((s1,s2))
>>>s3
'aWhatEverb'
Here is the code for string concatenation: `
String1 = "a"
String2 = "b"
String3 = String1 + String2
#String 3 would be ab
` You can add more than two string variables into one string variable.