我希望我的输出是:
Enter a number : n
List from zero to your number is : [0,1,2,3, ... , n]
0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list)
但我的实际输出是:
Enter a number : 5
List from zero to your number is : [0, 1, 2, 3, 4, 5]
[+0+,+ +1+,+ +2+,+ +3+,+ +4+,+ +5+] = 15
我正在使用 join
因为它是我唯一知道的类型。
为什么加号印在项目周围,为什么加号周围是空格?
我应该如何将 list
的值打印成字符串以供用户阅读?
谢谢。这是我的代码:
##Begin n_nx1 application
n_put = int(input("Choose a number : "))
n_nx1lst = list()
def n_nx1fct():
for i in range(0,n_put+1):
n_nx1lst.append(i)
return n_nx1lst
print ("List is : ", n_nx1fct())
print ('+'.join(str(n_nx1lst)) + " = ", sum(n_nx1lst))
最佳答案
将 list
中的每个 int
元素更改为 .join
调用中的 str
,而不是使用一个生成器表达式
:
print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))
在第一种情况下,您是在整个 list
上调用 str
,而不是在 list
中的单个元素上调用。结果,它将列表中的每个字符连接起来,如下所示:
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
+
符号产生您所看到的结果。
关于python - 用 '+' 加入字符串中的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38595362/