Help With map() *He says while pulling his hair out*

Paul Prescod paulp at
Mon Jul 9 07:07:35 CEST 2001

EricIDLE wrote:
> Ok first off I have a wee problem with one of the examples in my book it is
> as follows:
> s=""
> ls = string.split(s, '.')
> md = map(string.atoi, ls)
> Ok. well the problem is basically the whole thing. I know s=""
> is just defining the varible 's' with the numbers. 

It is defining a variable "s" as a *string*. Python doesn't know or care
that the string happens to have things that look like numbers to you or
me. It is just a bunch of characters.

> But my first problem is
> after string.split in its argument I know what the S means but I dont know
> what the '.' means does that mean to remove all the periods?

No. It means to split on the periods and return a *list of strings*.
Here's what Python's manual says:

split(s[, sep[, maxsplit]]) 

Return a list of the words of the string s. If the optional second
argument sep is absent or None, the words are separated by arbitrary
strings of whitespace characters (space, tab, newline, return,
formfeed). If the second argument sep is present and not None, it
specifies a string to be used as the word separator. The returned list
will then have one more item than the number of non-overlapping
occurrences of the separator in the string. The optional third argument
maxsplit defaults to 0. If it is nonzero, at most maxsplit number of
splits occur, and the remainder of the string is returned as the final
element of the list (thus, the list will have at most maxsplit+1

> The second problem is that I dont quite grasp the map() function what
> exactly does it do, In its argument it says in lamens terms "Turn the string
> ls into intergers" my problems is wasent it always intergers? 

No. It was strings. This is a string "12". This is an integer: 12. Play
around a little on the Python command line:

>>> 12
>>> "12"
>>> type(12)
<type 'int'>
>>> type("12")
<type 'string'>
>>> import string
>>> string.atoi("12")
>>> string.atoi(12)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "", line 214, in atoi
    return _int(s, base)
TypeError: ...

Take a recipe. Leave a recipe.  
Python Cookbook!

More information about the Python-list mailing list