rearrange text
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Wed Mar 2 10:48:03 EST 2005
Daniel Skinner wrote:
> If I have the following text
>
> var = '1,2,3,4'
>
> and I want to use the comma as a field delimeter and rearrange the
> fields to read
>
> '1,3,2,4'
>
> How would I accomplish this in python?
I take it you want to swap the second and the third element? That can be
accomplished by splitting into a list of fields, swap the second and
third element, join the fields back to a string:
>>> var = '1,2,3,4'
>>> fields = var.split(',')
>>> fields
['1', '2', '3', '4']
>>> fields[1], fields[2] = fields[2], fields[1]
>>> fields
['1', '3', '2', '4']
>>> newvar = ','.join(fields)
>>> newvar
'1,3,2,4'
--
"Codito ergo sum"
Roel Schroeven
More information about the Python-list
mailing list