简体   繁体   中英

How to read multiple inputs separated by space in a single line in Python 3.8?

I am trying to read multiple inputs in python separated by space. All of them are integers, float or double. Is there a way to get that done in python 3.8

You can try this

var = input.split(" ")

Above code will create an array of string.

for eg given input 1 2 3 4 5 , it'll create an array of var with elements ["1", "2", "3", "4", "5"]

Note that the above code will store each element as a string. If you want to change the data type of the elements you can use map function.

var_integers = list(map(int, input.split()))

This'll create an array of integer. Taking above example of 1 2 3 4 5 , it'll create an array var_integers with elements [1, 2, 3, 4, 5]

You can use any function in place of int in map function to transform the iterable (here input().split() creates a list of string elements as stated above which acts as an iterable) passed as a second argument.

For example if you use float instead of int then the input string will be converted to float then stored in array.

You can also store the elements directly into variable instead of storing in an array by:

var1, var2, var3 .. ,varn = map(int, input().split())

Here you have to specify exact number of variables as the number of elements separated by space in the input string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM