Automate the boring stuff with Python: Comma Code

前端 未结 29 956
深忆病人
深忆病人 2021-02-03 16:17

Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:

相关标签:
29条回答
  • 2021-02-03 16:50

    No loops, no joins, just two print statements:

    def commalist(listname):
        print(*listname[:-1], sep = ', ',end=", "),
        print('and',listname[-1])
    
    0 讨论(0)
  • 2021-02-03 16:52

    I was not satisfied with any of the solutions because none handle the case with or, e.g. apples, bananas, or berries

    def oxford_comma(words, conjunction='and'):
        conjunction = ' ' + conjunction + ' '
    
        if len(words) <= 2:
            return conjunction.join(words)
        else:
            return '%s,%s%s' % (', '.join(words[:-1]), conjunction, words[-1])
    

    Otherwise, this solution is more-or-less identical to the one provided by @PM2Ring

    0 讨论(0)
  • 2021-02-03 16:54

    My interpretation of the question is such that a single list item would also be the last list item, and as such would need the 'and' inserted before it, as well as a two item list returning both with ', and' between them. Hence no need to deal with single or two item lists seperately, just the first n items, and the last item. I'd also note that while great, a lot of the other items use modules and functions not taught in the Automate the Boring Stuff text by the time the student encounters this question (a student like me had seen join and .format elsewhere, but attempted to only use what had been taught in the text).

    def commacode(passedlist):
        stringy = ''
        for i in range(len(passedlist)-1):
            stringy += str(passedlist[i]) + ', '
            # adds all except last item to str
        stringy += 'and ' + str(passedlist[len(passedlist)-1])
        # adds last item to string, after 'and'
        return stringy
    

    And you could handle the empty list case by:

    def commacode(passedlist):
        stringy = ''
        try:
            for i in range(len(passedlist)-1):
                stringy += str(passedlist[i]) + ', '
                # adds all except last item to str
            stringy += 'and ' + str(passedlist[len(passedlist)-1])
            # adds last item to string, after 'and'
            return stringy
        except IndexError:
            return '' 
            #handles the list out of range error for an empty list by returning ''
    
    0 讨论(0)
  • 2021-02-03 16:54

    I am working through the same book and came up with this solution: This allows the user to input some values and create a list from the input.

    userinput = input('Enter list items separated by a space.\n')
    userlist = userinput.split()
    
    def mylist(somelist):
        for i in range(len(somelist)-2): # Loop through the list up until the second from last element and add a comma
            print(somelist[i] + ', ', end='')
        print(somelist[-2] + ' and ' + somelist[-1]) # Add the last two elements of the list with 'and' in-between them
    
    mylist(userlist)
    

    Example:

    user input: one two three four five Output: one, two, three, four and five

    0 讨论(0)
  • 2021-02-03 16:54
    spam=['apple', 'banana', 'tofu','cats']
    spam[-1]= 'and'+' '+ spam[-1]
    print (', '.join((spam)))
    
    0 讨论(0)
  • 2021-02-03 16:55

    The format statement is cleaner.

    This worked for me as well:

    def sentence(x):
        if len(x) == 1:
            return x[0]
        return (', '.join(x[:-1])+ ' and ' + x[-1])
    
    0 讨论(0)
提交回复
热议问题