gdogg371
gdogg371

Reputation: 4132

Replace every third comma with line break

I have some data of the following format:

var =  1,2,3,4,5,6,7,8,9

If I use the following code:

var = var.replace(',', '\n')
print var

I get an output like this:

1
2
3
4
5
6
7
8
9

What I want to get though is an output like this:

123
456
789

Which would involve only replacing every third comma with a line break. Is there a way to do this? I'ver had a look at some of the other questions on here and they don't seem to be addressing exactly what I am trying to do.

Thanks

Upvotes: 1

Views: 8145

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180471

var = "1,2,3,4,5,6,7,8,9"

spl = var.split(",") # split into list of individual items

print "\n".join(["".join(spl[i:i+3]) for i in range(0,len(spl),3)]) # join into chunks of 3 and add a newline to separate the output
123
456
789

To keep the commas:

"\n".join([",".join(spl[i:i+3]) for i in range(0,len(spl),3)])

Upvotes: 6

yurisich
yurisich

Reputation: 7119

Don't use replace, try var.split(',') and get a list.

From there, break it up into chunks of three, and then put a newline between those chunks.

I'll leave the actual coding up to you.

Upvotes: 3

Related Questions