[Tutor] Number Coercion: I swear, I never laid a hand on it!

Sean 'Shaleh' Perry shalehperry@home.com
Wed, 24 Oct 2001 10:49:01 -0700 (PDT)


> 
> menu choices
> ['vim', 'edit']
> vim
> Bad command or file name
> Traceback (most recent call last):
>   File "menu.py", line 14, in ?
>     os.system("s%")% menu_items[choice]
> TypeError: number coercion failed
> 

which takes us back to Remco's mail.  The syntax is:

"%s" % menu_items[choice].  This is analogous to C's sprintf (and printf, etc).
 I always say this on the list and will say it again.  When things break, run
the interpreter and play in it.

>>> foo = 'Sean' 
>>> "%s" % foo
'Sean'
>>> def bar(input):
...     print input
... 
>>> bar("%s") % foo
%s
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: bad operand type(s) for %

Here you can see the % error.

> The confusing thing to me is:
> 
>>>> menu_items={'edit': "\windows\command\edit.com",
>       'vim': "\vim\vim57\gvim.exe"}
>>>> choice="vim"
>>>> choice
> 'vim'
>>>> menu_items[choice]
> '\vim\vim57\gvim.exe'
> 
> seems to be giving the correct answer! Am I nuts?

>>> t = '\vim\vim57\gvim.exe'
>>> print t

im
  im57\gvim.exe
>>> 

the backslash is used to escape characters.  You can solve this in one of two
ways:

>>> t = r'\vim\vim57\gvim.exe'
>>> t
'\\vim\\vim57\\gvim.exe'
>>> t = '\\vim\\vim57\\gvim.exe'
>>> t
'\\vim\\vim57\\gvim.exe'

The 'r' before the quotes says "This is a raw string, do not look at it, just
save it".  You see this most in python when people are doing regular
expressions which have all kinds of odd characters.

The moral?  Watch the syntax a little more and when things get confusing use
the interpreter to find the answer.  What makes python (and langauges like it)
great is that you have instant feedback.