Conversion of perl based regex to python method

Peter Otten __peter__ at
Thu May 25 08:25:08 CEST 2006

Andrew Robert wrote:


> perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'  somefile.txt


> # Evaluate captured character as hex
> def ret_hex(ch):
>     return chr((ord(ch) + 1) % )

Make it compile at least before posting :-)
> # Evaluate the value of whatever was matched
> def eval_match(match):
>     return ret_hex(
> # open file
> file = open(r'm:\mq\mq\scripts\testme.txt','r')
> # Read each line, pass any matches on line to function
> for line in file.readlines():
>     re.sub('[^\w\s]',eval_match, line)

for line in file:

without readlines() is better because it doesn't read the whole file into
memory first. If you want to read data from files passed as commandline
args or from stdin you can use fileinput.input():

import re
import sys
import fileinput

def replace(match):
    return "%%%2X" % ord(

for line in fileinput.input():
    sys.stdout.write(re.sub("[^\w\s]", replace, line))


More information about the Python-list mailing list