On 12/19/2009 11:34 PM, Richard Hultgren wrote:
Hello,
I am a newcomer, I guess I'm have trouble thinking like a computer yet.
My question is:
in this program:

 resp = raw_input("What's your name? ")

 >>> print "Hi, %s, nice to meet you" % resp

does %s mean 'place the user response here'

No. %s means "call str() on the {first|second|third|etc} element of the tuple on the right-hand side of % operator, and put it in here".

The str type overloads %-operator to mean "string interpolation". Basically what it does is this:

>>> a = 1
>>> b = 2
>>> c = 4
>>> '%s %s %s' % (a, b, c)
'1 2 4'

but for convenience, if the right-hand side of the %-operator contains a non-tuple argument, then it will just call str() on the right-hand argument and put it in place of the %s.

>>> nottuple = 10
>>> 'hello %s world' % nottuple
'hello 10 world'

you may learn that instead of tuple, you can also use dict with %(name)s:

>>> '%(a)s %(foo)s' % {'a': 'hello', 'foo': 'world'}
'hello world'

and you may also learn later that instead of 's', you can also use other format codes like %f, %d, %x, %o. You can read more here: http://www.python.org/doc/2.5.2/lib/typesseq-strings.html

btw, you should also know that the recommended way to interpolate string is to use the new '{0} {1} {2}'.format(a, b, c)

and secondly what and why do
I put % resp at the end of the print statement? I know this is very
basic and future questiions will be more interesting I hope.

because python doesn't magically knows what string you want to put in place of %s. You need to specify that you want to put the value of `resp` in place of '%s'

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to