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 Antworten
+ 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