Home > Software design >  Read line seperated by space using python using stdin
Read line seperated by space using python using stdin

Time:11-11

I want to be able to write a size for a input and after that enter each number seperated by space which is less or equal than the size.

Like this:

First input (length): 3

inputs: 1 2 3

This should also be converted as an integer and stored in a list

I have tried this:

import sys


inputs = sys.stdin.readline()

print(len(inputs))

mynumbers = inputs.strip().split(' ')

newlist = [int(x) for x in mynumbers]

print(newlist)

#print(input.rstrip(''))

CodePudding user response:

You can pass the size to sys.stdin.readline() to limit the input by size.

import sys

size = int(input())

inputs = sys.stdin.readline(size * 2)
mynumbers = inputs.strip().split(' ')

newlist = [int(x) for x in mynumbers]
print(newlist)

CodePudding user response:

A first possible answer (without use of stdin but using input) could be:

size = int(input("First input (length): "))
print(size)
input_value = input("inputs (length): ")
mynumbers = input_value.strip().split(' ')
newlist = [int(x) for x in mynumbers[:size]]
print(newlist)

But I don't know if for you is mandatory the use of stdin.

CodePudding user response:

If you want to take input from user, use input(), not sys.stdin.*.

So you can just do something like this:

inputs = input().split()

nums = [int(x) for x in inputs]

print(inputs) # ['1', '2', '3']
print(nums) # [1, 2, 3]
  • Related