love233126 love233126 - 2 months ago 5
Python Question

python to split a long string into different rows

123|china|jack|342|usa|Nick|324345|spin|Amy


I want the end result like this(I know I need a new line for every 3 element):

123,china,jack
342,usa,Nick
324345,spin,Amy


Thank you

Answer

Try that:

x = '123|china|jack|342|usa|Nick|324345|spin|Amy'

l = x.split('|')
new_l = [l[i:i+3] for i in range(0,len(l),3)]

This will give you:

>>> for i in new_l:
...     print ','.join(i)
...
123,china,jack
342,usa,Nick
324345,spin,Amy
Comments