[Tutor] List element with replace

Jeff Shannon jeff@ccvcorp.com
Wed Apr 23 12:36:45 2003


Henry Steigerwaldt wrote:

>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
>

Ah, but you're using two different data types in your two cases.  Your 
mexT[0] is actually a list, while in your second example s is a string. 
 You can apply the string method replace() to each element of the list 
at mexT[0], but you need to be explicit about that:

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

You may then need to convert the list back into a string:

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

By the way, simply as a matter of style, I'd prefer to be doing all of 
this massaging using a temporary name, instead of stuffing each step 
back into mexT[0].

temp = mexT[0].split()[1:]
temp = [ item.replace("|", "") for item in temp ]
mexT[0] = " ".join(temp)

This makes for a slightly clearer distinction between the intermediate 
steps and the finished product.

Jeff Shannon
Technician/Programmer
Credit International