Question

Let's say I have a string like:

data = '''Random digits: (1|2|3), (4|5|6), (7|8|9).'''

How can I get output like:

Random digits: 1, 6, 7.

or

Random digits: 3, 4, 9.

So the idea is to choose each element randomly. (||) could be more than 3. Thank's in advice!

Was it helpful?

Solution

Try re.sub with a replacing function:

import re, random

def rand_replace(m):
    return random.choice(m.group(1).split('|'))

data = '''Random digits: (1|2|3), (4|5|6), (7|8|9).'''    
print re.sub(r'\((.+?)\)', rand_replace, data)

This also works for non-digit strings, like "(nice|good) (day|night)". If you want to be specific, this regexp:

r'\(([\d|]+)\)'

accepts only digits and pipes.

OTHER TIPS

from random import choice
import re

test = '''Random digits: (1|2|3), (4|5|6), (7|8|9).'''

def get_rc(data):
    tokens = data.split(",")
    chosen = list()
    for part in tokens: chosen.append(choice(re.findall("[0-9]+",part)))

Try it out:

>>> get_rc(test)
['2', '5', '9']
>>> get_rc(test)
['1', '4', '7']
>>> get_rc(test)
['1', '6', '7']
>>> get_rc(test)
['3', '5', '8']
>>> get_rc(test)
['1', '6', '9']
>>> get_rc(test)
['1', '4', '8']
>>> get_rc(test)
['2', '4', '9']

Most Pythonian:

def get_rc2(data):
    return [ choice(re.findall("[0-9]+",i)) for i in data.split(",") ]

If you want to get integers returned instead of numbers as string:

def get_rc2(data):
    return [ int(choice(re.findall("[0-9]+",i))) for i in data.split(",") ]

Trivially from your example. A more complicated version would split on '(' and ')' and then on '|'.

from random import choice
data = '''Random digits: (1|2|3), (4|5|6), (7|8|9).'''
print "Random digits: " + choice(data[16:21:2]) + ", " + choice(data[25:30:2]) + ", " + choice(data[34:39:2])

Something like this:

import re
import random

data = '''Random digits: (1|2|3), (4|5|6), (7|8|9).'''

random_digits = list()
for group in (m.strip('()').split('|') for m in re.findall(r'\([\d\|]+\)', data)):
    random_digits.append(random.choice(group))

print 'Random digits: ' + ', '.join(random_digits)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top