I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a for loop:
for x in range(5):
print(x, end=",")
The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:
0,1,2,3,4,
How do I remove the ending ,?
Pass sep="," as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep parameter as well as end.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.
>>> print("hello", "world")
hello world
Changing sep has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
You can use str.join() and create the string you want to print and then print it. Example -
print(','.join([str(x) for x in range(5)]))
Demo -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join .
To do that, you can use str.join().
In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4
We will need to convert the numbers in range(5) to string first to call str.join(). We do that using map() operation. Then we join the list of strings obtained from map() with a comma ,.
Another form you can use, closer to your original code:
opt_comma="" # no comma on first print
for x in range(5):
print (opt_comma,x,sep="",end="") # we are manually handling sep and end
opt_comma="," # use comma for prints after the first one
print() # force new line
Of course, the intent of your program is probably better served by the other, more pythonic answers in this thread. Still, in some situations, this could be a useful method.
Another possibility:
for x in range(5):
if x:
print (", ",x,end="")
else:
print (x, end="")
print()
for n in range(5):
if n == (5-1):
print(n, end='')
else:
print(n, end=',')
An example code:
for i in range(10):
if i != 9:
print(i, end=", ")
else:
print(i)
Result:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for x in range(5):
print(x, end=",")
print("\b");
Related
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?
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?)
You want to say
for i in array:
print(i, end=" ")
The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).
You can get the same effect with print(" ".join(map(str,array))).
Try using join on a str conversion of your ints:
print(' '.join(str(x) for x in array))
For python 3.7
these will both work in Python 2.7 and Python 3.x:
>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
btw, array is a reserved word in Python.
You have multiple options, each with different general use cases.
The first would be to use a for loop, as you described, but in the following way.
for value in array:
print(value, end=' ')
You could also use str.join for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.
print(' '.join(str(value) for value in array))
My favorite method, however, would be to pass array as *args, with a sep of ' '. Note, however, that this method will only produce a printed output, not a value that may be stored to a variable.
print(*array, sep=' ')
If you write
a = [1, 2, 3, 4, 5]
print(*a, sep = ',')
You get this output: 1,2,3,4,5
# Print In One Line Python
print('Enter Value')
n = int(input())
print(*range(1, n+1), sep="")
lstofGroups=[1,2,3,4,5,6,7,8,9,10]
print(*lstofGroups, sep = ',')
don't forget to put * before the List
For python 2.7 another trick is:
arr = [1,2,3]
for num in arr:
print num,
# will print 1 2 3
you can use more elements "end" in print:
for iValue in arr:
print(iValue, end = ", ");
Maybe this code will help you.
>>> def sort(lists):
... lists.sort()
... return lists
...
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9
you can use an empty list variable to collect the user input, with method append().
and if you want to print list in one line you can use print(*list)
I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))
I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))
I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))
I want to be able to rewrite the code in as few lines as possible, possibly in list comprehension syntax. Here is what the output should be:
1|2|3
4|5|6
7|8|9
This is what I have thought up. The separator doesn't actually print the "|". Any suggestions?
for i in [1,2,3,4,5,6,7,8,9]:
print(i, sep = "|", end = "")
if (i) % 3 == 0:
print()
>>> numbers = range(1, 10)
>>> print(('{}|{}|{}\n' * 3).format(*numbers))
1|2|3
4|5|6
7|8|9
Just print it.
>>> print('1|2|3\n4|5|6\n7|8|9')
1|2|3
4|5|6
7|8|9
To clarify: Yes, I'm obviously assuming that really exactly these numbers shall be printed. I think it's a reasonable assumption, given that the OP also only showed those numbers both in the desired output and in the code, didn't say anything about more flexibility (really should have if it were required), and tic-tac-toe has X and O, not numbers. I suspect this is for showing the user which number to enter for which field during play.
I like format the most because it offers the best flexibility:
moves = [' ', ' ',' ',' ', 'x',' ',' ', ' ','o']
board = "|{}|{}|{}|\n|{}|{}|{}|\n|{}|{}|{}|\n"
print(board.format(*moves)
Modify the items in that list and run that same print statement for an on-the-go solution.
And there, I managed to slim it down to 3 lines. If I wasn't initializing the list, it would only be 2 lines.
the easiest and most elegant way to do it in python 3 using print:
for i in 1,4,7:
print(i,i+1,i+2, sep='|')
Or using range:
for i in range(1,10,3):
print(*range(i,i+3), sep='|')
Also there is a good reading here about iterable unpacking operator: Additional Unpacking
Also here is one-liner, not the shortest one but very readable:
print('\n'.join(('{}|{}|{}'.format(i,i+1,i+2) for i in (1,4,7))))
And original one-liner from #Stefan Pochmann's comment:
print(('{}|{}|{}\n' * 3).format(*range(1, 10)), end='')
Output for all is the same:
1|2|3
4|5|6
7|8|9
print('\n'.join(['|'.join([str(c) for c in s[i:i+3]]) for i in range(0,9,3)]))
Don't use this (but it works). This assumes your array is in a variable named s
If you want something that is purely the smallest amount of lines, you can use the ternary syntax:
for i in range(1,10):
print(i,end='|\n') if (i) % 3 == 0 else print(i,end = "|")
Output:
1|2|3
4|5|6
7|8|9
sep doesn't work when you only give a single thing to print
>>>print(1, sep='|')
1
>>> print(1,2,3, sep='|')
1|2|3
Could do this instead
for i in range(1,10):
if i % 3 == 0:
print(i, end="\n")
else:
print(i, end="|")
Shortening to a ternary
for i in range(1,10):
print(i, end="\n") if i % 3 == 0 else print(i, end="|")
Output
1|2|3
4|5|6
7|8|9
If we're going to code golf, lets code golf properly...
One line:
print("".join(str(i)+'\n|'[i%3>0]for i in range(1,10)))
You can make it one character shorter when you realise that the indexer >0 is actually longer than repeating the pipe (|):
print("".join(str(i)+'\n||'[i%3]for i in range(1,10)))
This gives:
1|2|3
4|5|6
7|8|9
If you need even shorter, a for loop technically doesn't need to be on a new line, also in Python 3 print will print every *args, until the *kwargs.
for i in range(1,10,3):print(i,i+1,i+2,sep='|')
pass # Pass not needed, just shows syntactically how it works.
The first line above is probably the shortest you can get, without just printing the string as is.