How to transform str into int?

Asked

Viewed 2,397 times

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?

  • What is the result you expect to get?

  • I was hoping to get the first 0

  • Wouldn’t it be better to separate the value into two variables, like pontuacaoUm = 0 and pontuacaoDois = 0?

  • if it is 0 x 1 would be 0

  • score or multiply that?

  • even score, take the first number

Show 1 more comment

2 answers

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

You are not signed in. Login or sign up in order to post.