Reputation: 400
I was trying to take 3 integer inputs on the same line using split, but it throws an error
int() argument must be a string, a bytes-like object or a number, not 'list'
Here is my code
n,a,k = int(input().split())
Upvotes: 3
Views: 3287
Reputation: 8740
You can also accomplish the same using the below procedural approach even if your input contains alphabets with at least 3 numbers or more.
If you will enter a string with less than 3 numbers also, function wil take care of it and return 0 for the corresponding variables. Examples are included at very bottom. Please have a look.
import re
def get_inputs(n=3):
inp = input('Enter a sentence with at least 3 numbers included: ').strip()
arr = re.sub(r'[^0-9]+', ' ', inp).strip().split()
if len(arr) < n:
for i in range(n):
try:
arr[i]
except IndexError as e:
arr.append(0)
n, a, k, *rest = list(map(int, arr))
return (n, a, k, rest)
# Start
if __name__ == "__main__":
# Get 3 numbers
out1 = get_inputs()
n, a, k, rest = out1
print('n =', n)
print('a =', a)
print('k =', k)
print('rest = ', rest)
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: Hello, I like 65, 45 and 90 ok.
n = 65
a = 45
k = 90
rest = []
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 12, 23 and 67 are nice but 34 and 23 also.
n = 12
a = 23
k = 67
rest = [34, 23]
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 12 34 56
n = 12
a = 34
k = 56
rest = []
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 45 12 34 21 12 hello 99
n = 45
a = 12
k = 34
rest = [21, 12, 99]
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python 1.py
Enter a sentence with at least 3 numbers included: Now 67 is best for me.
n = 67
a = 0
k = 0
rest = []
Upvotes: 0
Reputation: 1518
You may want to use map
like so :
n,a,k = map(int, input().split())
as the split
function returns a list
and not a str
.
map
applies the int
function to every element (str
) of the list
.
Upvotes: 1
Reputation: 71570
OR:
import ast
n,a,k = ast.literal_eval(','.join(input().split()))
print(n,a,k,sep='\n')
Example Output:
1 2 3
1
2
3
Upvotes: 0
Reputation: 44344
Since others have given a map
solution, here is one using a simple list comprehension:
n,a,k = [int(i) for i in input().split()]
Does it have an advantage over map()
? Not really, but some prefer this approach.
Upvotes: 1
Reputation: 190
Please try
n,a,k = map(int, input().split())
int
can receive one string only.
Upvotes: 3