[Tutor] Re: List element with replace

Christopher Smith csmith@blakeschool.org
Wed Apr 23 23:01:22 2003


Henry Steigerwaldt hsteiger@comcast.net  writes:

>What am I doing wrong with this code? For some
>reason, I get the error below when trying to remove
>the "|" character from an existing line of numbers stored
>in a list element. 
>
>First in line 2, I remove the x/n from the numbers that
>are stored in the list element by using the "split" method. 
>Then mexT[0] will contain   "74| 51  79| 41  60|" as
>verified with the output using the print statement in line 4.
>So far so good.
>
>But in line 5, I attempt to remove the "|" character from the
>line of numbers by using the "replace" method, and hopefully
>store this result back into mexT[0], but that nasty error
>occurs below about "list object has no attribute replace."
>
>line 1   >>>  mexT[0] = "x/n  74|  51  79|  41  60|"
>line 2   >>>  mexT[0] = mexT[0].split()[1:]

While mexT[0] is a string, the result of the split operation is
a list.  And the complaint that 'lists don't have a replace' method
is raised.  Without knowing all the manipulations you are going to 
do to the list it is hard to anticipate the best solution for 
getting rid of the '|' characters.  If all you want to do is
get rid of the 'x/n' and the '|' characters then converting the list
to a string, doing the replacements, and converting it back to a list
might be an option:  

###
>>> l
['x/n 74| 51| 79| 41 60|', 1]
>>> str(_) # convert to a string; the '_' refers to the last output
"['x/n 74| 51| 79| 41 60|', 1]"
>>> _.replace('x/n','') #do replacements
"[' 74| 51| 79| 41 60|', 1]"
>>> _.replace('|','')
"[' 74 51 79 41 60', 1]"
>>> eval(_, {}) # convert back to list, not giving eval() access to
anything
[' 74 51 79 41 60', 1]
###

/c