rearrange text

D

Daniel Skinner

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

Roel Schroeven

Daniel said:
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'
 
S

Simon Brunning

If I have the following text

var = '1,2,3,4'

and I want to use the comma as a field delimeter

That bit's easy:

C:\WINNT\system32>python
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.['1', '2', '3', '4']
and rearrange the
fields to read

'1,3,2,4'

I don't really understand this rearrangement, but I'll do it the dumb way:
rearranged_var = split_var[0], split_var[2], split_var[1], split_var[3]
rearranged_var
('1', '3', '2', '4')

Then you can join it all up again like so:
'1,3,2,4'
 
D

Daniel Skinner

ah thanks I couldn't figure out how to join it up very appropriately,
had this loop ... yeeeaah .. :)

Thanks for both comments
 
R

Russell Blau

Daniel Skinner said:
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?

Well, it kind of depends on how you want to do the rearranging, whether the
data in the fields is always going to be numbers or could be some other kind
of object, etc.

In general, though, what you seem to be looking for is:

mylist = var.split(',')
rearrange(mylist)
newvar = ','.join(mylist)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,222
Messages
2,571,137
Members
47,753
Latest member
LilianMcIl

Latest Threads

Top