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

前端 未结 3 954
深忆病人
深忆病人 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)))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题