How To Separate Numbers By Space In Python

In this tutorial, we will learn how to separate numbers in a list or a string by space in Python. This can be useful in various applications, such as formatting data for better readability, preparing data for further processing, or simply extracting numbers from text.

Step 1: Understand the given data

First, let’s understand the data that we are working with. We can be given a list of numbers or a string containing numbers that need to be separated by spaces. For example:

List of numbers:

[1, 2, 3, 4, 5]

A string containing numbers:

"12345"

Step 2: Separate numbers in a list by space

To separate the numbers in a list by space, simply use the join() function on the list, and then use the format() method to convert each number into a string. Here’s a code snippet that demonstrates this:

Output:

1 2 3 4 5

Step 3: Separate numbers in a string by space

If given a string containing numbers, use the join() function in combination with a list comprehension to separate the characters (i.e., the digits) in the given string. Here’s a code snippet that demonstrates this:

Output:

1 2 3 4 5

Step 4: Test the solution with different inputs

Now let’s test the solution with different inputs to make sure it works as expected:

Output:

10 20 30 40 50 60
9 8 7 6 5 4 3 2 1 0

Full code example

Output

10 20 30 40 50 60
9 8 7 6 5 4 3 2 1 0

Conclusion

In this tutorial, we have learned how to separate numbers in a list or a string by space in Python. The approach we used can be easily applied to various data types, and we’ve tested it with different inputs to ensure its functionality. Now you can use these techniques in your own projects to format and process numerical data more effectively.