格式化字符串更易于阅读

时间:2014-02-05 21:32:19

标签: python

我正在寻找一种更优雅的方式将字符串格式化为人类可读的语法。

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

到目前为止我得到了什么:

>>> 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'

2 个答案:

答案 0 :(得分:3)

你可以用以下方法一行:

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

在python 3中使用:"-".join([a[i:i+4] for i in range(int(len(a)/4))])

答案 1 :(得分: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')

返回

ABCD-EFGH-IJKL-MNOP-QRST-UVWX