[Tutor] List element with replace

Emil Styrke emil@lysator.liu.se
Wed Apr 23 05:37:07 2003


Henry Steigerwaldt <hsteiger@comcast.net> writes:

> To All:
>
> 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:]
> line 3   >>>  print mexT[0]
> line 4   >>>  ['74|', '51', '79|', '55', '79|']
> line 5   >>>  mexT[0] = mexT[0].replace("|", "")
>
> Traceback (most recent call last):
>   File "<pyshell#8>", line 1, in ?
>     mexT[0] = mexT[0].replace("|", "")
> AttributeError: 'list' object has no attribute 'replace'
>>>>
>
> Yet, if I use a variable instead of a list element, say "s" and 
> use in place of mexT[0], no error occurs.
>
> Example:  s  =  "74|  51  79|  41  60|"
>                 s = s.replace("|", "")
>                 print s
>                 74  51  79  41  60
>  
> How does one use a list element with the replace method as in the
> example above?


It could be done with a for loop or list comprehension:

>>> for i in range(len(mexT[0])):
...     mexT[0][i] = mexT[0][i].replace("|", "")

or

>>> mexT[0] = [ i.replace("|", "") for i in mexT[0] ]

Another option is to first convert the list back to a string with the
join method:

>>> mexT[0] = " ".join(mexT[0])

    /Emil
    
> Thanks much. 
>
> Henry Steigerwaldt
> Hermitage, TN
> Email:  hsteiger@comcast.net
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor