[Tutor] Question about string

Alan Gauld alan.gauld at btinternet.com
Thu Jul 3 11:18:23 CEST 2008

"Dong Li" <dongli2020 at gmail.com> wrote

> I am new to python, so what I ask may be so basic. I don't know the
> difference between
> s = 'a' 'b'
> and
> s = 'a'+'b'
> They have the same results. Thanks for relying!

I think the differencec is that the first is purely a syntax thing so
the interpreter does the work of joining the strings together before
processing the result as a single string whereas the second the
two strings are treated separately and actual string addition
(concatenation) is done which is a much more expensive
operation in terms of computer power.

The first is only possible if you have literal strings but the second
can be used for variables:

s1 = 'a'
s2 = 'b'
s = s1 s2     # doesn't work
s = s1 + s2   # works


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list