+ 1
Converting List items into text
write a function that returns below list as 'apple, banana, lemon, cake and eggs'. this is how I did it, asking for your suggestion/feedback/constructive criticism: def lists(value): value.insert(len(value)-1,'and') for i in range(len(value)): if i < (len(value)-3): print(value[i],end = ', ') elif i <= len(value): print(value[i], end =' ') stuffs = ['apple','banana','lemon','cake','eggs'] lists(stuffs) I'm a beginner, if you have better suggestion using the above concepts pls comment.
3 Réponses
+ 2
Hey, it does exactly what it's supposed to do, good job!
There's a convenient method of str, that allows you to glue parts together with a specific substring: join.
I would do it like this:
def lists(value):
return ' and '.join(
(', '.join(stuffs[:-1]), stuffs[-1])
)
stuffs = ['apple','banana','lemon','cake','eggs']
print(lists(stuffs))
It first joins all but the last element with ', ' and finally joins that part with the last element using ' and '.
And then it's usually cleaner to not print the data from the function, but to return it and let the outer scope decide what to do with this string (maybe you want to write it to a file or store it in a list or whatever).
0
I didn't completely understand join (I've just completed a chapter on lists). This is little advance for me, but I got your suggestion about using print outside function. I will keep that in mind. Thanks :)
0
This is so simple...if only I would've come across join earlier. Now I get it, thanks!