Automate the boring stuff with Python: Comma Code

前端 未结 29 988
深忆病人
深忆病人 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:34

    As it was not mentioned, here's an answer with f string, for reference:

    def list_things(my_list):
        print(f'{", ".join(my_list[:-1])} and {my_list[-1]}.')
    

    An example interpolating a custom message and accepting also a string as argument:

    def like(my_animals = None):
        message = 'The animals I like the most are'
        if my_animals == None or my_animals == '' or len(my_animals) == 0:
            return 'I don\'t like any animals.'
        elif len(my_animals) <= 1 or type(my_animals) == str:
            return f'{message} {my_animals if type(my_animals) == str else my_animals[0]}.'
        return f'{message} {", ".join(my_animals[:-1])} and {my_animals[-1]}.'
    
    
    >>> like()
    >>> like('')
    >>> like([])
    # 'I don't like any animals.'
    
    >>> like('unicorns') 
    >>> like(['unicorns']) 
    # 'The animals I like the most are unicorns.'
    
    >>> animals = ['unicorns', 'dogs', 'rabbits', 'dragons']
    >>> like(animals) 
    # 'The animals I like the most are unicorns, dogs, rabbits and dragons.'
    

提交回复
热议问题