The following code should take strings in for form of #d# and roll a random number based on the dice then replace #d# with #.
For example 1d6 would roll 1 6-sided die and replace 1d6 with, say, a 5.
# Turn dice notation into a number
def parse_dice(string):
# Replace all dice notations #d# with a number #
matches = re.findall("[0-9]+d[0-9]+", string)
for match in matches:
a = match.split("d", 1)[0]
b = match.split("d", 1)[1]
roll = str(roll_dice(int(a), int(b)))
print("String is: " + string + "\nThe match is: " + match + "\nI'll replace it with the roll: " + roll)
string.replace(match, roll)
print("After replacing I got: " + string)
# Parse any leftover math tacked on
number = eval(string)
return number
The print statements are for testing. Here's an example output:
String is: 1d6
The match is: 1d6
I'll replace it with the roll: 2
After replacing I got: 1d6
For some reason, even though the string matches the string I'm replacing EXACTLY it won't replace it so at the end I'm running eval("1d6") instead of eval("5")