简体   繁体   中英

List based printing python removing the last comma

I have a list of elements : answer = [1,4,2,4] I need to output the list elements two at a time with spaces separated by a comma: EXPECTED OUTPUT : 1 4,2 4

CODE:

for i in range(0,len(ans),2):
    print(ans[i],ans[i+1],end=",")

Output: 1 4,2 4, I cannot remove that last frigging comma.

Assumption: The list is even.

Logic: Just detect the last iteration of the code and don't print comma there.

ans = [1,5,6,7,8,9]

for i in range(0,len(ans),2):

  last_iteration = len(ans)-(2) # Here 2(is same as the step size used in the loop)

  if i==last_iteration:  
    print(ans[i],ans[i+1])

  else: 
    print(ans[i],ans[i+1],end=",")

Output:

1 5,6 7,8 9

This works

ans = [1,4,2,4]
print(",".join([str(ans[i])+ " " + str(ans[i+1]) for i in range(0, len(ans),2)]))
>>> 1 4,2 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM