Randomize Elements Positions Defined between "<" and ">" Symbols Using Regular Expressions

Question:

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)
Asked By: texture

||

Answers:

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)

Try it online!

Answered By: Kelly Bundy
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.