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'
Use the + operator The + operator can be used to concatenate two different strings.
To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial. For example, you can assign a character 'a' to a variable single_quote_character .
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.
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With