Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a newline character every 64 characters using Python

Tags:

python

regex

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?

like image 287
bignum Avatar asked Apr 17 '10 07:04

bignum


1 Answers

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.

like image 59
AndiDog Avatar answered Sep 21 '22 02:09

AndiDog