Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Creating commas in string but leaving out one comma transferred from list

So I'm creating a function that takes a list and turns it into a string. I want commas and place the word "and" at the end, which I got working. However I want a spot between tofu and cats where there is no comma, which is my dilemma. Here's the code so far:

#Write a function that takes list value as an argument and return a string

spam = ['apples', 'bananas', 'tofu', 'cats']

def comma_code (comma):
    comma.insert (-1, 'and')
    join_string = ",  ".join(comma)
    print (join_string)
print (comma_code(spam))

Yes this is from "How to Automate the Boring Stuff"

1 Answer

Steven Parker
Steven Parker
243,656 Points

I'm assuming you mean between "and" and "cats" (instead of "tofu" and "cats"). One way would be to rsplit (right-split) on the final comma and then rejoin with a blank separator:

    join_string = "".join(", ".join(comma).rsplit(",", 1))

If you want to eliminate both the commas before and after "and", change that 1 to a 2.

I'm unfamiliar with rsplit... so it puts in a comma and what's the 1 for?

Steven Parker
Steven Parker
243,656 Points

It's like "split" but working right-to-left, and it's to take out the comma(s). The 1 (or 2) is the limit on how many splits to perform.