[Tutor] How to remove the comma only at the end?

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jan 24 12:45:53 EST 2020


On 24/01/2020 13:12, Panchanathan Suresh wrote:

> How to remove the last comma , from the variable members?
> I tried members[:-1], 

That will remove the last character from a string but....

>   for x in range(0,len(users)):
>       members = members + users[x] + ", "

You are adding a comma and a space at the end, so your
code will remove the space but not the comma.

However, you are probably better using the rstrip()
method of the string

return members.rstrip(', ')

Or maybe you are better not using a string at all?
Would a dictionary be a better fit and then only
convert to a string on output? Especially if you
plan on having multiple departments.

If you really want a string you could use join:

def group_list(group, users):
  members = group +": "
  return members + ','.join(users)

Which only inserts the comma between the inner members.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list