python - 用 '+' 加入字符串中的列表项

标签 python list python-3.x

我希望我的输出是:

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/

相关文章:

java - 将整数数组列表转换为基于ascii表的字符串并与字符串进行比较

html - 滚动时在页面顶部制作 Jquery 移动列表分隔符 "stick"

Python 多重处理仅在首次运行后才快速

python - TypeError:实例 Python 之间不支持 '<'

python - 使用ffmpeg从两个视频中同时提取帧

python - 在 Pandas 中跨多个文件迭代简单计算

c - 我们如何在C语言中将list(Python中的)函数实现为数组?

python - 将混合数据转换为字符串 numpy

python - 设置 Spyder 工作区和项目的基础知识

python - 将行从scrolled_window复制到剪贴板