Insert a newline character every 64 characters using Python

后端 未结 7 2170
無奈伤痛
無奈伤痛 2020-12-01 17:46

Using Python I need to insert a newline character into a string every 64 characters. In Perl it\'s easy:

s/(.{64})/$1\\n/

How could this be

7条回答
  •  一向
    一向 (楼主)
    2020-12-01 18:43

    itertools has a nice recipe for a function grouper that is good for this, particularly if your final slice is less than 64 chars and you don't want a slice error:

    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)
    

    Use like this:

    big_string = 
    output = '\n'.join(''.join(chunk) for chunk in grouper(big_string, 64))
    

提交回复
热议问题