Home > front end >  Splitting a string into smaller strings using split()
Splitting a string into smaller strings using split()

Time:02-01

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, ' ')

CodePudding user response:

You can use a regular expression for this instead of splitting the string up. Just capture each numeric position with a group. Check out the docs on the re package for details.

Here's a sample:

import re

pattern = r"(?P<rolls>\d )d(?P<sides>\d )\ (?P<add>\d )"
match = re.match(pattern, input_text)
rolls = int(match["rolls"])
sides = int(match["sides"])
add = int(match["add"])

With input_text as "4d6 12" as in your example, the resulting values are:

print(rolls) # 4
print(sides) # 6
print(add) # 12

CodePudding user response:

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=}")
  •  Tags:  
  • Related