I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:
#gets the string string = input('Input numbers: ') #converts the string into an array of int, excluding the whitespaces array = [int(s) for s in string.split()]
Apparently it works, since when I type in '1 2 3' and do a print(array)
the output is:
[1, 2, 3]
But I want to print it in a single line without the brackets, and with a space in between the numbers, like this:
1 2 3
I've tried doing:
for i in array: print(array[i], end=" ")
But I get an error:
2 3 Traceback (most recent call last):
print(array[i], end=" ")
IndexError: list index out of range
How can I print the list of ints (assuming my first two lines of code are right) in a single line, and without the brackets and commas?
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.
Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.
Yes that is possible in Python 3, just use *
before the variable like:
print(*list)
This will print the list separated by spaces.
(where *
is the unpacking operator that turns a list into positional arguments, print(*[1,2,3])
is the same as print(1,2,3)
, see also What does the star operator mean, in a function call?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With