-1

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")

Tuckertcs
  • 29
  • 5

1 Answers1

1

replace() returns a copy of the string where all occurrences of a substring is replaced.

You cannot mutate (modify) a string in python. Even if you want badly. Strings are immutable datatype by design, so, please, create a new string. The proper use is

string2 = string.replace(....

well, as Thierry suggested, you can store that new string in the same variable

string = string.replace(...
Serge
  • 3,387
  • 3
  • 16
  • 34