0

I'm looking for a more elegant way to format a string into a human readable syntax.

>>> a = 'ABCDEFGHIJKLMNOPQRSTUVWX'
>>> # magic
>>> print(a)
'ABCD-EFGH-IJKL-MNOP-QRST-UVWX'

What I got so far:

>>> a = 'ABCDEFGHIJKLMNOPQRSTUVWX'
>>> b = map(''.join, zip(*[iter(a)]*4))
>>> print(b)
['ABCD', 'EFGH', 'IJKL', 'MNOP', 'QRST', 'UVWX']
>>> c = '-'.join(b)
>>> print(c)
'ABCD-EFGH-IJKL-MNOP-QRST-UVWX'
zvisofer
  • 1,346
  • 18
  • 41
Thomas Schwärzl
  • 9,518
  • 6
  • 43
  • 69
  • For what its worth, I think what you have there is rather good. But if you're looking for alternatives supplying some concrete criteria (speed, memory usage, etc) would be helpful – wnnmaw Feb 05 '14 at 21:34
  • 1
    possible duplicate of [Python - concatenated string to a tuple](http://stackoverflow.com/questions/21351275/python-concatenated-string-to-a-tuple) – Ashwini Chaudhary Feb 05 '14 at 21:35
  • To be honest - no speed or memory criteria at all. I just thought "hmmm, it wouldn't be the first time to see some 'better' solution at stackoverflow" – Thomas Schwärzl Feb 05 '14 at 21:37
  • @init3, well the solution in the possible duplicate is gorgeous, so you should check that out (even though you've already accepted an answer here) – wnnmaw Feb 05 '14 at 21:56

2 Answers2

3

You can do it in one line with this:

>>> a = 'ABCDEFGHIJKLMNOPQRSTUVWX'
>>> "-".join([a[i:i+4] for i in range(len(a)/4)])
 'ABCD-BCDE-CDEF-DEFG-EFGH-FGHI'

In python 3 use: "-".join([a[i:i+4] for i in range(int(len(a)/4))])

jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
2
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def make_elegant(s, groupsize=4, joiner='-', pad=''):
    return joiner.join(''.join(block) for block in grouper(s, groupsize, pad))

print make_elegant('ABCDEFGHIJKLMNOPQRSTUVWX')

returns

ABCD-EFGH-IJKL-MNOP-QRST-UVWX
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99