How to transform str into int?

1

I tried to make the score into int as I did in JavaScript but it did not work:

placar = "0 x 0"
print(int(placar))

I expected it to show 0 but resulted in an error, how do I turn the scoreboard into int ?

    
asked by anonymous 31.10.2017 / 20:58

2 answers

5

What you are doing does not make sense, as the string 0 x 0 is not a valid numeric format, so it results in the error.

To get the two values that make up the scoreboard, you can use the split method of string :

placar = '0 x 2'
a, b = map(int, placar.split(' x '))

See working at Ideone | Repl.it

So,% with% will be worth 0, first value of the score, and% with% will be worth 2, second value of the score, both of type a .

Now, if the format of this string can vary, for example, b , no spaces, int , with more than one space, etc, it might be more viable to parse 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)
    
31.10.2017 / 21:06
1

If you want to show 0 in the answer, you can do it like this:

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])

Note: This only works when the board is in AxB format, where A and B are 0-9.

If the value of one of the results is greater than 9, you can do this by working statically:

placar = "0 x 21"

valor = int(placar[0])
valor2 = int(placar[4:6])

print(valor)
print(valor2)

Output:

0
21
    
31.10.2017 / 21:06