Join items of a list with '+' sign in a string

前端 未结 3 1071
深忆病人
深忆病人 2020-12-18 09:35

I would like my output to be :

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)
         


        
3条回答
  •  独厮守ぢ
    2020-12-18 10:19

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

    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.

提交回复
热议问题