Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining two string variables [duplicate]

Tags:

python

I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined:

a = 'lemon' b = 'lime' 

Can someone tell me how to combine these in a new variable?

If I try:

>>> soda = "a" + "b" >>> soda 'ab' 

I want soda to be 'lemonlime'. How is this done?

Thanks!

like image 889
Jay Avatar asked Jul 08 '10 15:07

Jay


People also ask

How do you combine string variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

How do you join two variables in Python?

Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

How do you combine strings and variables in Python?

How to Concatenate Strings in Python. In the code above, we created two variables ( x and y ) both containing strings – "Happy" and "Coding" – and a third variable ( z ) which combines the two variables we created initially. We were able to combine the two variables by using the + operator.


2 Answers

you need to take out the quotes:

soda = a + b 

(You want to refer to the variables a and b, not the strings "a" and "b")

like image 130
froadie Avatar answered Oct 18 '22 22:10

froadie


IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.']) 

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

like image 34
GreenMatt Avatar answered Oct 18 '22 22:10

GreenMatt