Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining of strings in a list

Tags:

python

list

I have a list in python:

A = ['5', 'C', '1.0', '2.0', '3.0', 'C', '2.1', '1.0', '2.4', 'C', '5.4', '2.4', '2.6', 'C', '2.3', '1.2', '5.2']

I want to join A in a a way where output looks like:

5\n
C 1.0 2.0 3.0\n
C 2.1 1.0 2.4\n
C 5.4 2.4 2.6\n
C 2.3 1.2 5.2

''.join(A) joins every string together, '\n'.join(A) joins every string starting from new line. Any help for this? Thanks!

like image 668
Habib Avatar asked Nov 25 '25 15:11

Habib


2 Answers

You can loop through, or just do something like this:

' '.join(A).replace(' C', '\nC')

The space in the replace string is really important to prevent a leading empty line if the first char is a 'C', and to prevent trailing whitespace in other places. (Thanks @aruisdante)

like image 182
kitti Avatar answered Nov 27 '25 05:11

kitti


I'd probably employ some itertools functionality.

from itertools import izip

def chunks(iterable, num=2):
  it = iter(iterable)
  return izip(*[it] * num)

print '\n'.join([A[0]] + [' '.join(c) for c in chunks(A[1:], 4)])
like image 31
g.d.d.c Avatar answered Nov 27 '25 03:11

g.d.d.c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!