Attach list items with a "+" in a row

I would like my conclusion 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)

But my actual conclusion is:

Enter a number : 5
List from zero to your number is :  [0, 1, 2, 3, 4, 5]
[+0+,+ +1+,+ +2+,+ +3+,+ +4+,+ +5+] =  15

I use joinas this is the only type I know.

Why do plus signs print around elements and why do they surround empty spaces?

How to print values listin a line for reading by the user?

Thank. Here is my code:

##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))
+4
source share
3 answers

Change each individual element intin listto strinside the call .joinusing generator expression:

print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))    

str list, list. , :

'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

+, , .

+6

str . str- , '+'.

map, str, join:

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

:

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

, string "+" . , , - .

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

:

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

?
, (5.1.3) ( ), int , list string. string join(), .

>>> [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'
+4

Source: https://habr.com/ru/post/1649190/


All Articles