-1
def calculate_average():

mylist = []

for i in range (10):
    input = int(input("Enter an integer: "))
    mylist.append(integer)

avg = sum(numbers) / len(numbers)

aboveavg = ([x for x in numbers if x > average])

print("\nThe average is:", avg)
print("Numbers greater than average:")
print(str(aboveavg).strip('[]'))

I get an output for the very last line where it has a comma. For example

Numbers greater than average:
14, 15

Instead of:

14 15

How to go about fixing the code? Do I use join? (something I haven't learned about in class yet)

tabi
  • 45
  • 6
  • .replace will 'fix' your code vs .strip. duplicate question: https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x –  Jan 15 '18 at 18:54
  • Why exactly are you showing us all that code for building `aboveavg` (and not showing us input for it)? Should we care? – Stefan Pochmann Jan 15 '18 at 19:00

5 Answers5

2

You could use join, which concatenates a string before printing it:

print(' '.join(str(elt) for elt in aboveavg))

or a for loop where you print one element at a time on the same line:

for elt in aboveavg:
    print(str(elt), end=' ')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
1

Yup, you should use str.join in this case. It is the built-in way to achieve this:

print(' '.join(map(str, aboveavg)))
# or:
print(' '.join([str(x) for x in aboveavg]))

It is important to note that you can only join str objects. You will have to convert the elements of the iterable you want to join to str. You can use either map or a comprehension to achieve that.

user2390182
  • 72,016
  • 6
  • 67
  • 89
1

You can do this easily

print(" ".join([str(x) for x in aboveavg]))
BitParser
  • 3,748
  • 26
  • 42
1

Yes. Since the result is a list, you can create a string from a list by using join:

print (' '.join(map(str, your_list)))
Matej
  • 932
  • 4
  • 14
  • 22
0

No idea why everybody's joining...

print(*aboveavg)
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • `join` is definitely the tool to know. It is more flexible, e.g you can further process the resulting str, whereas `print` just prints. – user2390182 Jan 15 '18 at 19:01