[Tutor] really dumb questions [string concatenation/string formatting]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 15 Feb 2002 01:23:51 -0800 (PST)


On Fri, 15 Feb 2002, kevin parks wrote:

> f.writelines(map(lambda s: s+'\n', ["Scooby", "Dooby", "Doo"]))
> 
> This worked as is, the problem was that i tried to say:
> 
> x=['scooby', 'dooby', 'doo']
> 
> f.writelines(map(lambda s: s+'\n', x))
> 
> and that doesn't work it says:
> 
> TypeError: unsupported opperand types for +: 'int' and 'str'


Hmmm, that's odd!  I would have expected this error message if our 'x'
list contained an integer somewhere in there.  The error message:

> TypeError: unsupported opperand types for +: 'int' and 'str'

is saying something to the effect "I'm trying to add up an integer and a
string!  Help!"  The only thing I can think of is that, somehow, an
integer slipped into the list by mistake.  Can you check to see if this is
possible?


Here's an example that shows what might be happening:

###
>>> mylist = ['one', 'two', 3]
>>> for element in mylist:
...     print 'strike ' + element
... 
strike one
strike two
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
TypeError: cannot concatenate 'str' and 'int' objects
###


On the 3rd strike, it's way out.  So string concatenation is a bit strict
about being aware of the types of our values.  Strings stick together with
strings, and are quite prudish when it comes to string concatenation.


However, strings relax a little when we use string formatting:

###
>>> mylist = ['one', 'two', 3]
>>> for element in mylist:
...     print 'counting %s' % (element,)
... 
counting one
counting two
counting 3
###

The '%s' part tells Python to use the "string" representation of the
element when plugging things in, no matter what, and in most cases, that's
probably what we want.


Anyway, hope you're having a pleasant holiday.  I can't wait for the three
day weekend here in the States... *grin*