Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - 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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...