[Tutor] replacing spaces and tabs before the code

Kent Johnson kent37 at tds.net
Sun Nov 6 14:13:56 CET 2005


Ìúʯ wrote:
>  I am try to write a code that turn codes to html file

You might be interested in existing solutions. Here is an old list, there are probably more now:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/904b11321e07460a/fc9a13cf4baf3b05%23fc9a13cf4baf3b05?sa=X&oi=groupsr&start=1&num=3
Pudge is a new one:
http://pudge.lesscode.org/

> I do it like this,(It is take out from example code form sourceforge):
> 
> re_lead=re.compile(r"[\f\t]")
> re_space=re.compile(r"[ ]{2,}")
> src = re_lead.sub(r"&nbsp&nbsp&nbsp&nbsp ",src)         
> src = re_lead.sub(r"&nbsp&nbsp&nbsp&nbsp ",src)         
> 
>   src is the code string!
>   as you can see, I repeat the search many time to replace two or more \t before the code line.
>   but, if somebody use space, some time may be up to 8 or 9 times before a line,it 
> would be stupid to repeat 8 time of search to replace them!
>   It's there a method that can replace  all spaces with "&nbsp" just at one search 
> action, and pass the single space between words!

re.sub() can take a function (or any callable) as the 'replacement' parameter.  The function gets a Match object as its argument and returns the replacement string. This is very handy when you need to do some processing on the match to figure out what the correct replacement string is.

Here is an example that looks at the length of the match and returns a corresponding number of   (BTW your example is missing the final semicolon - should be ' ')
 >>> import re
 >>> spaceRe = re.compile(r'^( +)')
 >>> def spaceRepl(m):
 ...   num = len(m.group(1))
 ...   return ' '*num
 ...
 >>> spaceRe.sub(spaceRepl, '    def foo():')
'    def foo():'

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list