1
I tried to turn the score into int
as I did in Javascript but it didn’t work:
placar = "0 x 0"
print(int(placar))
I expected it to show 0 but it resulted in a mistake, as I do to turn the score into int
?
1
I tried to turn the score into int
as I did in Javascript but it didn’t work:
placar = "0 x 0"
print(int(placar))
I expected it to show 0 but it resulted in a mistake, as I do to turn the score into int
?
5
What you’re doing makes no sense, because the string 0 x 0
is not a valid numeric format, so results in error.
To get the two values that form the scoreboard, you can use the method split
of string:
placar = '0 x 2'
a, b = map(int, placar.split(' x '))
See working on Ideone | Repl.it
Thus, a
will be worth 0, first score, and b
will be worth 2, second score value, both of type int
.
Now, if the shape of this string may vary, for example, 0x0
, space-free, 0 x 0
, with more than one space, etc., maybe it is more feasible to analyze through a regular expression:
import re
placar = "0x0"
groups = re.match("(\d+)\s*x\s*(\d+)", placar)
if groups:
a, b = int(groups[1]), int(groups[2])
print(a, b)
a lot of dough that way using this re
1
If you want it to show 0 in the answer, you can do it this way:
placar = "0 x 0"
print(int(placar[0]))
Output: 0
If you want to store each value in a variable:
valor = int(placar[0])
valor2 = int(placar[4])
Obs: So it only works when the score is in format AxB
, where A and B are 0 to 9.
If the value of one of the results is greater than 9, you can do so by working statically:
placar = "0 x 21"
valor = int(placar[0])
valor2 = int(placar[4:6])
print(valor)
print(valor2)
Output:
0
21
Browser other questions tagged python type-conversion
You are not signed in. Login or sign up in order to post.
What is the result you expect to get?
– Woss
I was hoping to get the first 0
– Matheus Silva Pinto
Wouldn’t it be better to separate the value into two variables, like
pontuacaoUm = 0
andpontuacaoDois = 0
?– gato
if it is 0 x 1 would be 0
– Matheus Silva Pinto
score or multiply that?
– Don't Panic
even score, take the first number
– Matheus Silva Pinto