'Splitting a string into smaller strings using split()

I'm trying to write a D&D dice roller program in Python. I'd like to have the input be typed in the form "xdy+z" (ex. 4d6+12, meaning roll 4 6-sided di and add 12 to the result), and have the program "roll the dice", add the modifier, and output the result. I'm trying to figure out how to split the string into numbers so I can have the program do the math.

I know of the split() function, and I'm trying to use it. When I input the example above, I get the string [4 6 12], but when I have the program print string[1], I get a white space because it's still one full string. I'd either like to figure out how to get the program to identify the individual numbers in the string, or a way to split the full string into smaller strings (like string1 = [4], string2 = [6], string3 = [12]).

Yes, I tried Google and searching this site, but I'm not sure what the terminology for this type of process is to it's been hard to find help.

Here's the relevant code:

separators = ["d", "+", "-"]
for sep in separators:
     inputText = inputText.replace(sep, ' ')


Solution 1:[1]

Solution without regular expressions, using find, slicing and split. First, find the position of + or - to get the last number. Then, split the rest at d. Also, convert the partial strings to int:

s = "4d6+12"

if "-" in s:
    pos = s.find("-")
    add = int(s[pos:])
elif "+" in s:
    pos = s.find("+")
    add = int(s[pos:])
else:
    add = 0
    pos = len(s)

rolls, sides = map(int, s[:pos].split("d"))

print(f"{rolls=} {sides=} {add=}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wups