0

I am trying to loop every element of a list, and append each element of the list to a string in the format like aa, bb, cc, dd, ee, ....

My loop is like this:

    string = "" 

    for num in sorted(list):
       string = "xyz" + "-" + str(list[num])
       string = string + ", "

    return string

The format it output is like xyz - 1, xyz - 3, xyz -6,

How can I end up without last comma in a format like xyz - 1, xyz - 3, xyz -6 ?

Rodia
  • 1,407
  • 8
  • 22
  • 29

2 Answers2

2

Instead of constructing the string yourself, you can use str.join:

string = ', '.join("xyz-"+str(x) for x in sorted(list))

.join is called on a string that acts as a separator: it will be inserted between the elements (but not after the last element). In the join you need to provide an iterable (list, tuple, set, generator,...) that provides strings that should be joined together.

In this case we wrote an iterator that will, for every x in the sorted(list) generate a string "xyz-"+str(x) and these products will be joined together.


ERRORS?

There is furthermore probably an error in your code:


for num in sorted(list):
    string = "xyz" + "-" + str(list[num])

If you use a for over a list, you get the elements, not the indices. So it should be num instead of list[num].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

use str.join and a list comprehension to avoid doing this:

return ", ".join(["xyz-{}".format(num) for num in sorted(lst)])

(and note that your code has other issues than that: using list as a variable, doing lst[num] where num is needed are 2 examples)

(([ is not a typo: creating a list comprehension and not a generator comprehension allows join to work faster: List vs generator comprehension speed with join function)

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219