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

Cameron Simpson cs at cskk.id.au
Fri Jan 24 14:34:07 EST 2020


On 24Jan2020 05:12, Panchanathan Suresh <suresh.gm at gmail.com> wrote:
>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,

Note that your code is adding ", ", so there is a comma and a space.  

Using "members[:-1]" only skips the space. -2 would help.

Likewise, rstrip strips trailing commas, but there are no trailing 
commas, only a trailing space.

If you:

    print(repr(members))

as a debugging statement, this would become more evident.

Personally, I prefer not to strip the trailing stuff, but to only add 
the separator on the second and following members. Eg:

    if members:
        members += ', '
    members += users[x]

That way there is never a trailing separator.

However, I recommend what others have suggested: use str.join.  

Incrementally extending string is ok for small strings, but as the lis 
of users gets bigger the cost gets significantly larger because the 
members string gets copied at each append, leading to O(n^2) behaviour 
in the long term.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list