I am trying to randomize elements positions that are defined between "<" and ">" brackets, eg. from this
<id:1 s= red>
<id:2 s= blue>
<id:3 s= green>
to this
<id:3 s= green>
<id:1 s= red>
<id:2 s= blue>
I put them in a list but can't match back the randomized list with the regex results. Here is what I got so far:
import re
from random import shuffle
a = open('data.txt', 'r')
s= a.read()
x = re.findall(r'\<([^>] )', s)
shuffle(x)
f = re.sub(r'\<([^>] )', x[0], s)
print(f)
CodePudding user response:
Making your attempt work:
x = re.findall(r'(<[^>] )', s)
shuffle(x)
f = re.sub(r'(<[^>] )', lambda _: x.pop(), s)
How I prefer to do it:
x = re.split(r'(<[^>] )', s)
y = x[1::2]
shuffle(y)
x[1::2] = y
f = ''.join(x)