Automate the boring stuff with Python: Comma Code -
currently working way through beginners book , have completed 1 of practice projects 'comma code' asks user construct program which:
takes list value argument , returns string items separated comma , space, , inserted before last item. example, passing below spam list function return 'apples, bananas, tofu, , cats'. function should able work list value passed it.
spam = ['apples', 'bananas', 'tofu', 'cats']
my solution problem (which works fine):
spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): new_string = '' in list: new_string = new_string + str(i) if list.index(i) == (len(list)-2): new_string = new_string + ', , ' elif list.index(i) == (len(list)-1): new_string = new_string else: new_string = new_string + ', ' return new_string print (list_thing(spam))
my question, there way can shorten code? or make more 'pythonic'?
use str.join()
join sequence of strings delimiter. if words except last, can insert ' , '
there instead:
def list_thing(words): if len(words) == 1: return words[0] return '{}, , {}'.format(', '.join(words[:-1]), words[-1])
breaking down:
words[-1]
takes last element of list.words[:-1]
slices list produce new list words except last one.', '.join()
produces new string, strings of argumentstr.join()
joined', '
. if there one element in input list, 1 element returned, unjoined.'{}, , {}'.format()
inserts comma-joined words , last word template (complete oxford comma).
if pass in empty list, above function raise indexerror
exception; test case in function if feel empty list valid use-case function.
so above joins all words except last ', '
, adds last word result ' , '
.
note if there 1 word, 1 word; there nothing join in case. if there two, 'word1 , word 2'
. more words produces 'word1, word2, ... , lastword'
.
demo:
>>> def list_thing(words): ... if len(words) == 1: ... return words[0] ... return '{}, , {}'.format(', '.join(words[:-1]), words[-1]) ... >>> spam = ['apples', 'bananas', 'tofu', 'cats'] >>> list_thing(spam[:1]) 'apples' >>> list_thing(spam[:2]) 'apples, , bananas' >>> list_thing(spam[:3]) 'apples, bananas, , tofu' >>> list_thing(spam) 'apples, bananas, tofu, , cats'
Comments
Post a Comment