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.

0

2 Answers 2

3

You can also try this-

s = "1 2"
a, b = (int(i) for i in s.split())
# a = 1, b = 2
Sign up to request clarification or add additional context in comments.

Comments

1

You can use map

Ex:

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

Output:

(1, 2)

1 Comment

You are welcome :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.