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

前端 未结 3 1073
深忆病人
深忆病人 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:17

    You don't need to call str on your list. That returns the str representation of your list and the output of that is joined with '+'.

    You can instead use map to convert each item in your list to str, then join:

    print('+'.join(map(str, n_nx1lst)) + " = ", sum(n_nx1lst))
    

    You can also use the new style formatting to have a more readable output:

    result = '+'.join(map(str, n_nx1lst))
    print("{} = {}".format(result, sum(n_nx1lst)))
    

提交回复
热议问题