[Tutor] Re: List element with replace
Jeff Shannon
jeff@ccvcorp.com
Thu Apr 24 16:37:02 2003
Christopher Smith wrote:
>[...] 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]
>###
>
Since it looks like this was only converted to a list as a side-effect
of removing the 'x/n', we can avoid a lot of ugly back-and-forth
conversions.
>>> mexT[0]
'x/n 74| 51 79| 41 60|'
>>> temp = mexT[0]
>>> temp = temp.replace('x/n', '')
>>> temp
' 74| 51 79| 41 60|'
>>> temp = temp.replace('|','')
>>> temp
' 74 51 79 41 60'
>>> temp = temp.strip()
>>> temp
'74 51 79 41 60'
>>> mexT[0] = temp
>>> mexT[0]
'74 51 79 41 60'
>>>
If the end result really should leave mexT[0] as a list, then a simple
split() will do the trick. This lets us avoid the use of eval(), which
is generally a bad idea to use unless there's no other way to accomplish
your task (i.e., almost never).
Jeff Shannon
Technician/Programmer
Credit International