How to use specific parts of a string from input() ? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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