Python - How to add space on each 3 characters?

前端 未结 4 1892
后悔当初
后悔当初 2021-01-22 12:05

I need to add a space on each 3 characters of a python string but don\'t have many clues on how to do it.

The string:

345674655

The ou

4条回答
  •  不要未来只要你来
    2021-01-22 12:31

    You just need a way to iterate over your string in chunks of 3.

    >>> a = '345674655'
    >>> [a[i:i+3] for i in range(0, len(a), 3)]
    ['345', '674', '655']
    

    Then ' '.join the result.

    >>> ' '.join([a[i:i+3] for i in range(0, len(a), 3)])
    '345 674 655'
    

    Note that:

    >>> [''.join(x) for x in zip(*[iter(a)]*3)]
    ['345', '674', '655']
    

    also works for partitioning the string. This will work for arbitrary iterables (not just strings), but truncates the string where the length isn't divisible by 3. To recover the behavior of the original, you can use itertools.izip_longest (itertools.zip_longest in py3k):

    >>> import itertools
    >>> [''.join(x) for x in itertools.izip_longest(*[iter(a)]*3, fillvalue=' ')]
    ['345', '674', '655']
    

    Of course, you pay a little in terms of easy reading for the improved generalization in these latter answers ...

提交回复
热议问题