[英]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?
我使用join吗? (something I haven't learned about in class yet)
(我在课堂上还没学到的东西)
You could use join, which concatenates a string before printing it: 您可以使用join,在打印之前将一个字符串连接起来:
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循环,您在同一行上一次打印一个元素:
for elt in aboveavg:
print(str(elt), end=' ')
Yup, you should use str.join
in this case. 是的,在这种情况下,您应该使用
str.join
。 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. 重要的是要注意,您只能连接
str
对象。 You will have to convert the elements of the iterable you want to join to str
. 您必须将要加入的可迭代元素转换为
str
。 You can use either map
or a comprehension to achieve that. 您可以使用
map
或comprehension来实现。
您可以轻松做到这一点
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:
由于结果是列表,因此您可以使用join从列表创建字符串:
print (' '.join(map(str, your_list)))
不知道为什么每个人都参加...
print(*aboveavg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.