num = 0
def regex(m):
num = num + 1
return '<iframe src="%s%s%s">' % (m.group(1), '/number/', num)
re.sub('<iframe src="(\w+)">', regex, source)
source is
<p>hogehogehello<br />aaaa</p><iframe src~~><div><strong><h1>aa</h1></strong></div><iframe~~~><iframe~~~><h2>aaaaaa</h2><iframe~~~>
result
UnboundLocalError: local variable 'num' referenced before assignment
ideal
<iframe src="https://youtube.com/hogehgoe/number/1">
<iframe src="https://youtube.com/hogehgoe/number/2">
<iframe src="https://youtube.com/hogehgoe/number/3">
<iframe src="https://youtube.com/hogehgoe/number/4">
<iframe src="https://youtube.com/hogehgoe/number/5">
source ideal is
<p>hogehogehello<br />aaaa</p>
<iframe src~~/1><div><strong><h1>aa</h1></strong></div>
<iframe~~~/2>
<iframe~~~/3><h2>aaaaaa</h2>
<iframe~~~/4>
I do not want to use finditer
if possible. I would like to complete with as short a code as possible.
I tried use global num. but Error SyntaxError: name 'bum' is assigned to before global declaration.