Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
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 Respostas
+ 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