randomhopeful randomhopeful - 4 months ago 7
Python Question

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

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)


Yet my actual output 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'm using
join
as it's the only type I know.

Why are the plus signs printed around the items and why are they surrounding blank spaces?

How should I print the
list
's values into a string for the user to read ?

Thank you. Here's 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))

Jim Jim
Answer

Change each individual element in the list to a str inside the .join call instead:

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 so it joins each character in the representation of the list:

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

with the + sign yielding the result you're seeing.

Comments