1

I have a String with 2 Integers separated by a space. How do I assign this to 2 variables?

s = "1 2"
num1, num2 = int(s.split())
print(num1, num2)

int() argument must be a string, a bytes-like object or a number, not 'list'

This code above is not working: I am getting an error.

s = "1 2"
num1: int
num2: int
num1, num2 = s.split()
print(num1 + num2)

This also doesn't seem to work. I am getting 12 as output (String concatenation)

I do not want to use int(num1) everywhere in the code.

Please help.

Rochan
  • 25
  • 1
  • 5

2 Answers2

3

You can also try this-

s = "1 2"
a, b = (int(i) for i in s.split())
# a = 1, b = 2
Sushant
  • 3,499
  • 3
  • 17
  • 34
1

You can use map

Ex:

s = "1 2"
num1, num2 = map(int, s.split())
print(num1, num2)

Output:

(1, 2)
Rakesh
  • 81,458
  • 17
  • 76
  • 113