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

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

    What you need to do is concatenate a string element with ' + ' for each element in your list. All you need from there is to have some string formatting.

    def sum_of_input():
        n = int(raw_input("Enter a number : "))  # Get our raw_input -> int
        l = range(n + 1)  # Create our list of range [ x≥0 | x≤10 ]
        print("List from zero to your number: {}".format(l))
        print(' + '.join(str(i) for i in l) + ' = {}'.format(sum(l)))
    

    Sample output:

    >>> sum_of_input()
    Enter a number : 10
    List from zero to your number: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
    

    How does it work?
    We use what's called a list comprehension (5.1.3) (generator in this specific usage) to iterate over our list of int elements creating a list of string elements. Now we can use the string method join() to create our desired format.

    >>> [str(i) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    >>> ' + '.join(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
    '1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10'
    

提交回复
热议问题