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

Mats Wichmann mats at wichmann.us
Fri Jan 24 13:12:12 EST 2020


On 1/24/20 6:12 AM, Panchanathan Suresh wrote:
> Hi everyone,
> 
> How to remove the last comma , from the variable members?
> I tried members[:-1], members.rstrip(","), but no luck. It is
> always returning:
> Mike, Karen, Jake, Tasha,
> 
> I want it to return Mike, Karen, Jake, Tasha (no comma after Tasha)
> 
> Below is my code:
> 
> *****
> def group_list(group, users):
>   members = ""
>   members1 = ""
>   for x in range(0,len(users)):
>       #print(users[x])
>       members = members + users[x] + ", "
>   return members[:-1]
> 
> 
> print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should
> be "Marketing: Mike, Karen, Jake, Tasha"

I'm going to jump in with my own comment here - you should cringe almost
any time you see  "for x in range(len(foo)):"

If users is something you can iterate over (as a list, it is), then
iterate over it.  Don't artifcially generate an item count, use range to
generate a NEW thing you can iterate over, and then index into the
original list.  You can write this more expressively as:

for user in users:
    members = members + user + ", "

and yes, if you're solving the problem this way, you wanted:

return members[:-2]    # because you put in two chars at the end!

that's line is not terribly expressive (-2 is "magic", avoid "magic"),
so how about if you define:

sep = ", "

then you can

return sep.join(users)

or

members = members + user + sep
...
return members[:-len(sep)]






More information about the Tutor mailing list