How To Take Space Separated Input In Python

In this tutorial, we will learn how to take space-separated input in Python 3. This is a common task when dealing with user input or when reading from data files containing values separated by spaces. We will explore using the input() function and the split() method to easily handle this type of input.

Step 1: Use the input() function to get user input

The first step in taking space-separated input is to use the input() function. This function allows the user to enter a string of text, which can then be processed as needed.

For example, to prompt the user to enter a space-separated list of numbers, you can use the following code:

In this example, input_str will store the string entered by the user.

Step 2: Split the input string using the split() method

Now that we have the input string, we need to break it up into individual values. To do this, we can use the split() method provided for strings in Python. By default, this method splits a string using spaces as the delimiter.

Here’s an example of how to use the split() method:

In this example, the split() method is called on the input_str string, and it returns a list of values separated by space characters.

Step 3: Convert the list of strings into a list of desired data type

The list returned by the split() method contains strings, but we often need to work with other data types, like integers or floating-point numbers. To convert the list of strings into a list of another data type, you can use the map() function in combination with a loop or list comprehension.

For example, to convert a list of strings into a list of integers, you can use the following code:

Similarly, to convert a list of strings into a list of floating-point numbers, you can use the following code:

Full Code

Here’s the full code to demonstrate how to take space-separated input in Python 3:

Output

Enter a list of space-separated numbers: 1 2 3 4 5
List of numbers: [1, 2, 3, 4, 5]

In this tutorial, we have demonstrated how to take space-separated input in Python 3 using the input() function, the split() method, and the map() function. These methods make it easy to process user input or read data from files containing space-separated values, allowing you to manipulate and work with the data in various ways.