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

Mark Lawrence breamoreboy at gmail.com
Fri Jan 24 12:40:19 EST 2020


On 24/01/2020 13:12, 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 = ""

Your for loop is poor Python, you should use:-

for user in users:

>    for x in range(0,len(users)):
>        #print(users[x])
>        members = members + users[x] + ", "
>    return members[:-1]

But you simply don't need the above, just the string join method 
https://docs.python.org/3/library/stdtypes.html#str.join hence using the 
interactive prompt:-

 >>> print("Marketing:", ', '.join(["Mike", "Karen", "Jake", "Tasha"]))
Marketing: Mike, Karen, Jake, Tasha

> 
> 
> print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should
> be "Marketing: Mike, Karen, Jake, Tasha"
> 
> *****
> 
> Thanks so much,
> Suresh

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list