Skip to main content

Be aware of the count 0 when using Pythons re sub to find and replace text


I have an xml file and I want to remove a whole section of element without actually parsing the XML file. I wrote an Python script to do just that. I first tested it out like this:

import re
input_text = open(my.xml).read()
result = re.findall(r<library-ref>.*</library-ref>, input_text, re.S)
print(result)


The result IS what I wanted, so I thought I can quickly replace it with something like this:

result = re.sub(r<library-ref>.*</library-ref>, , input_text, re.S)

And to my surprise this does not work. It took me a while to notice that I mis used the method according to the documentation, which has this signature:

re.sub(pattern, repl, string, count=0, flags=0)

At first glace, I thought that count is already default to zero and I do not need to set it, but because that is a positional parameter, you must include it! So you suppose to call it explicit like this:

result = re.sub(r<library-ref>.*</library-ref>, , input_text, 0, re.S)

Or, if you like, you can use the "flags" parameter name explicitly without the odd looking zero.

result = re.sub(r<library-ref>.*</library-ref>, , input_text, flags=re.S)

So here is an example of flexible dynamic typing of optional parameters can bite if you are not careful.

Popular posts from this blog

Baixar PS1 Crash Bandicoot 2 Cortex Strikes Back

PARTE 1: http://www.megaupload.com/?d=1AVO7X8T PARTE 2: http://www.megaupload.com/?d=WUBY6EAH

Battlefield 3 rwie głos

Masz Battlefield 3 i na Windows 7/8 rwie Tobie g?os. Jest na to spos�b i to bardzo prosty :D Wystarczy ?e dasz zgodno?? z Windows 95 (spowoduje to dzia?anie tylko na jednym core ale zawsze co?). Je?eli procesor masz wystarczaj?co dobry to ta metoda rozwi??e ten uci??liwy problem !

Baixar Jogo Download Mario Kart Double Dash Emulador de NGC PC

Na nova vers�o os gr�ficos ficaram bel�ssimos, o som simplesmente cativante, as musicas de cada cenario fasem a diferen�a na hora de jogar e embalam as corridas. A jogabilidade nem se fala, a possibilidade de fazer Dash (derrapada ou Drift) para ganhar velocidade � essencial para vencer, e ainda tem o fato de que jogamos com dois personagens em cada Kart, ou seja, podemos combinar Mario dirigido e Bowser atrapalhando os adversarios e no meio da corrida basta um toque no bot�o Z e eles mudam de posi��o. Cada dupla de personagem tem seu poder especial, Mario e Luigi tem bolas de foto, Koopa e Paratroopa tem cascos triplos, Bowser e seu filinho podem lan�ar cascos enormes e por ai vai. S�o varios personagens mais 2 destravaveis, os carros ent�o nem se fala, � um mais legal que outro cada um com seu diferencial. Sem d�vida nenhuma Mario Kart Double Dash � um marco para a hist�ria dos games e vale a pena jogar por muitas horas. :::Minima::: Core 2 Duo 8800 GT 1Gb de RAM :::Recomendada ...