2

I want to remove the ',' before the '<', and the last ',' that is being printed, but I'm not sure how.

It's like I'm repeating a print command, but I'd like the last element being printed to follow a different command.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
  if i < 5:
    print(i, end=' ,')
print('<', end=' ')
for i in a:
  if i > 5:
    print(i, end=' ,')

This is what is being printed:

1 ,1 ,2 ,3 ,< 8 ,13 ,21 ,34 ,55 ,89 ,

I want to remove those extra commas.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Possible duplicate of [Print in one line dynamically](https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically) – clabe45 Oct 10 '18 at 00:44

5 Answers5

3

You can use a generator expression with the sep parameter for print to print ' ,' as a separator instead of an ending string.

Change:

for i in a:
  if i > 5:
    print(i, end=' ,')

to:

print(*(i for i in a if i > 5), sep=' ,', end='')
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks for showing me the sep feature, but i'm curious to know why is it necessary an * at the beggining of the print command – Otavio TOP kakkakaka Oct 10 '18 at 02:20
  • The `*` operator is unpacking the items from the output of the generator expression so that the items can be passed as individual arguments to the `print` function. You can see https://www.python.org/dev/peps/pep-0448/ for details. – blhsing Oct 10 '18 at 03:23
1

A bit verbose but works:

 >>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
 >>> ", ".join(str(n) for n in a if n < 5) + " < " + ", ".join(str(n) for n in a if n >= 5)
'1, 1, 2, 3 < 5, 8, 13, 21, 34, 55, 89'

This concatenates string and makes use of str.join() which is useful to handle such comma-separated sequences smartly

Jens
  • 8,423
  • 9
  • 58
  • 78
0

You can remove the last item of the array when iterating, then just print the last element at the end.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a[:-1]:    # Iterate to n-1 element
  if i < 5:
    print(i, end=' ,')
print('<', end=' ')
for i in a[:-1]:    # Iterate to n-1 element
  if i > 5:
    print(i, end=' ,')
print(a[-1])        # Print last element
bunbun
  • 2,595
  • 3
  • 34
  • 52
0

You can use the str.join method to combine combine a bunch of strings into one, separated by the string you call it on. That will let you get your numbers separated by commas without adding an extra one on the end of each loop.

Here's how I'd do it all in one line:

print(" ,".join(str(n) for n in a if n < 5), "<", " ,".join(str(n) for n in a if n > 5))
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

Using .join(), .strip(), .replace()

s = ''.join(str(a))
s = s.strip('[]')
s = s.replace(' 5,',' <')
print(s)
# 1, 1, 2, 3, < 8, 13, 21, 34, 55, 89
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20