在字符串中以"+"号联接列表项 [英] Join items of a list with '+' sign in a string
问题描述
我希望输出为:
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
,因为它是我所知道的唯一类型.
I'm using join
as it's the only type I know.
为什么在项目周围打印加号?为什么在空格周围?
Why are the plus signs printed around the items and why are they surrounding blank spaces?
我应该如何将list
的值打印到字符串中以供用户阅读?
How should I print the list
's values into a string for the user to read ?
谢谢.这是我的代码:
##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
,而不是使用generator expression
:>
Change each individual int
element in the list
to a str
inside the .join
call instead by using a generator expression
:
print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))
在第一种情况下,您是在整个list
上而不是在该list
中的单个元素上调用str
.结果,它连接列表表示中的每个字符,如下所示:
In the first case, you're calling str
on the whole list
and not on individual elements in that list
. As a result, it joins each character in the representation of the list, which looks like this:
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
带有+
符号的
会产生您所看到的结果.
with the +
sign yielding the result you're seeing.
这篇关于在字符串中以"+"号联接列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!