Insert a newline character every 64 characters using Python


Question

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 done using regular expressions in Python? Is there a more pythonic way to do it?

1
23
4/17/2010 7:54:39 AM

Accepted Answer

Same as in Perl, but with a backslash instead of the dollar for accessing groups:

s = "0123456789"*100 # test string
import re
print re.sub("(.{64})", "\\1\n", s, 0, re.DOTALL)

re.DOTALL is the equivalent to Perl's s/ option.

30
4/22/2013 8:46:20 AM

without regexp:

def insert_newlines(string, every=64):
    lines = []
    for i in xrange(0, len(string), every):
        lines.append(string[i:i+every])
    return '\n'.join(lines)

shorter but less readable (imo):

def insert_newlines(string, every=64):
    return '\n'.join(string[i:i+every] for i in xrange(0, len(string), every))

The code above is for Python 2.x. For Python 3.x, you want to use range and not xrange:

def insert_newlines(string, every=64):
    lines = []
    for i in range(0, len(string), every):
        lines.append(string[i:i+every])
    return '\n'.join(lines)

def insert_newlines(string, every=64):
    return '\n'.join(string[i:i+every] for i in range(0, len(string), every))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon