How do you capture two integers with space between them in python3?

Asked

Viewed 812 times

-1

I want to capture two integers, example:

2 4

exactly so in python, but it by int(input()) normal n goes, I have done so, but must have another way:

var = input()
lista = []
lista = var.split(' ')
n,q = lista
n = int(n)
q = int(q)

2 answers

3

The function input will always return a string, regardless of the content read, then whether it is necessary to obtain two integers from a string, separated by a comma, the logic will be basically the same as when separated by a blank space: only the separator character changes.

For example:

entrada = input('Entre com dois números separados por vírgula:')
x, y = (int(numero) for numero in entrada.split(','))
print(x, y)

In this way, it is possible to enter entries in the form "2, 3", with the space between the comma and the number, because when converted to integer, the space will be ignored.

-2


With space, it would have to be something like this... But if it’s by comma, it could be like this:

[a,b]=list(input("Insira dois numeros separados por virgulas: "))
print "Numero 1:", a
print "Numero 2:", b

In the terminal:

Insira dois numeros separados por virgulas: 12,28
Numero 1: 12
Numero 2: 28
  • I found q so goes too, almost the same thing, but it gets more compact a,b = list(map(int,input(). split(' ')))

  • 1

    this answer without the "split" is simply wrong. Why is upvotes and accepts??

  • 4

    @Pythonfocus: Please, to improve the quality of the site, avoid "accept" an answer that doesn’t work - even if it inspires you to answer the right answer. Remember that other people will be checking this answer for reference - seeing "accepted" is assumed to be correct.

Browser other questions tagged

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