import sys\x0d n,M=sys.stdin.read(),'*'\x0d t=n.split()\x0d for y,l in enumerate(t):\x0d o = ''\x0d for x,v in enumerate(l):\x0d if v==M:\x0d o += M\x0d continue\x0d s = 0\x0d for j in xrange(y - 1, y + 2):\x0d for i in xrange(x - 1, x + 2):\x0d if j < 0 or i < 0:\x0d continue\x0d try:\x0d if t[j][i] == M:\x0d s += 1\x0d except IndexError:\x0d pass\x0d o += str(s)\x0d t[y]=o\x0d print '\n'.join(t)
Note that non-ascii characters in the above source code will be escaped (such as \x9f).