27

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!

Kevin
  • 74,910
  • 12
  • 133
  • 166
Jay
  • 325
  • 1
  • 5
  • 10
  • 11
    Welcome to StackOverflow. Good novice question -- you satisfied all the guidelines: show what you're trying to accomplish, show what you've tried, ask a specific question. +1 BTW, the terminology for "combining" two strings in this manner is "concatenation" (which is derived from Latin for "chain" as in "chain together"). – Jim Garrison Jul 08 '10 at 16:03
  • 1
    @Jim Garrison speaks the truth. Keep asking questions in this manner and you'll keep getting solid answers. – Wilduck Jul 08 '10 at 16:27

2 Answers2

47

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")

froadie
  • 79,995
  • 75
  • 166
  • 235
21

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.

GreenMatt
  • 18,244
  • 7
  • 53
  • 79