0

How to use specific parts of a string from input() ?

What I want to do is use specific parts from one single input for different bits of my code. For example: dice = input() #input will be ‘4d6’ I want to use the 4 as the amount variable and the 6 as the dieType variable. I of course could use: amount = int(dice[0]) But that doesn’t work when I use 12d4 as my input. How can I use the part before the ‘d’ and after the ‘d’ as input regardless of length of those ‘numbers’? Idea? I’m not that far along in coding so if you check my codes you can see what level I’m at :)

29th May 2019, 9:19 AM
Brave Tea
Brave Tea - avatar
7 Antworten
+ 2
Lothar has a good solution, but its cleaner to do this amount = int(dice[:dice.index("d")])
29th May 2019, 12:12 PM
Choe
Choe - avatar
+ 7
If the structure of your input is always as your samples you can use character ‘d’ in split. inp = list(input('some text: ').split('d')) # input 24d7 creates a list : [‘24’. ‘7’] Then you can use this list to access the values. First value : inp[0], second value: inp[1]. Depending on the further use of the values in the list you can convert them to int. x = int(inp[0]) y = int(inp[1]) If the use of the ‘d’ in your input does not have any influence for the programm, you can also omit ‘d’ and use a space instead. In this case you have to use ‘ ‘ (a space) in split().
29th May 2019, 9:29 AM
Lothar
Lothar - avatar
+ 4
Choe, really clean and short! Can you extend the code to get also the second part of the dice, means all what follows the ‘d’ on the right side?
29th May 2019, 3:18 PM
Lothar
Lothar - avatar
+ 3
Choe- thanks a lot!!
29th May 2019, 5:35 PM
Lothar
Lothar - avatar
+ 2
Lothar sure, dieType = int(dice[dice.index("d")+1:])
29th May 2019, 4:31 PM
Choe
Choe - avatar
0
Thank you both so much! I will try out both methods tonight.
29th May 2019, 4:38 PM
Brave Tea
Brave Tea - avatar
0
it works a treat! Thanks again! https://code.sololearn.com/cL31u8k3inkw/?ref=app
29th May 2019, 6:16 PM
Brave Tea
Brave Tea - avatar