Split Input by Space in Python

There are two key functions we need to use here: input(<prompt>) and str.split(<char>).

The input(<prompt>) is an inbuilt Python function that accepts the input from the user and converts it into a string. If <prompt> is given, it is printed on the output console.

The str.split(<char>) returns a list of words in the str by splitting it along the <char>.

Output:

Let’s now work on examples of how to use input() and str.split() functions.

Example 1: Taking input and splitting it

Output:

Input candidate's details: Tomasz 2719 79 87
Tomasz 2719 79 87
['Tomasz', '2719', '79', '87']

Example 2: Taking input, splitting it, and passing it into a function

In this example, the idea is to take exam candidate details as input, split the details into individual data points, and compute average marks scored. Candidate’s detail will contain the name of the candidate and the marks scores in different subjects.

Output:

Input candidate's details: Tomasz 97 87 88
['Tomasz', '97', '87', '88']
Tomasz 90.66666666666667

The *args attribute in the function definition above allows us to pass a variable number of positional arguments.

In the example above, we are inputting the name (Tomasz) and three marks (with args, you can give any number of marks) into the candidate variable, split the input into individual data points, and then unpack the data points into process_candidate() function.

Example 3: Taking input from the file and processing it

The idea in this example is to read input from a file and process the data as required. We will use the data.txt file with the following contents.

Tomasz 92 67 88

Ammon 64 69 70

Faith 56 70 67

Allan 88 72 74

The objective is to read the data from the file, loop through each line, and compute the average of the three scores for each candidate.

Output:

Tomasz [92, 67, 88] Mean: 82.33333333333333
Ammon [64, 69, 70] Mean: 67.66666666666667
Faith [56, 70, 67] Mean: 64.33333333333333
Allan [88, 72, 74] Mean: 78.0

Conclusion

This article discussed how to split input by space in Python. If the input is taken from the user keystrokes, then the input is read into Python using the input() function, and str.split(” “) is used to split the input on white space.

In example 2, we saw how input is fed to a function and processed, and in the third example, we discussed how to take input data from the file and process.