Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating one string from two in python

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'

like image 904
Matt Avatar asked Mar 08 '11 22:03

Matt


People also ask

How do I combine two strings in Python?

Use the + operator The + operator can be used to concatenate two different strings.

How do you make a single string in Python?

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 .

How do I combine multiple strings into one?

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 join 2 numbers in Python?

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.


2 Answers

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
like image 126
fredley Avatar answered Oct 18 '22 10:10

fredley


You could use the simplest version: String3 = String1 + String2 or the format operator (deprecated in python3): String3 = '%s%s' % (String1, String2)

like image 2
ThiefMaster Avatar answered Oct 18 '22 08:10

ThiefMaster