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 :)
7 Respuestas
+ 2
Lothar has a good solution, but its cleaner to do this
amount = int(dice[:dice.index("d")])
+ 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().
+ 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?
+ 3
Choe- thanks a lot!!
+ 2
Lothar sure,
dieType = int(dice[dice.index("d")+1:])
0
Thank you both so much!
I will try out both methods tonight.
0
it works a treat!
Thanks again!
https://code.sololearn.com/cL31u8k3inkw/?ref=app