简体   繁体   中英

How to remove a comma in an output

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)

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=' ')

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.

您可以轻松做到这一点

print(" ".join([str(x) for x in aboveavg]))

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

print (' '.join(map(str, your_list)))

不知道为什么每个人都参加...

print(*aboveavg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM