[codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.相关的知识,希望对你有一定的参考价值。

任务目标:

Given: an array containing hashes of names

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example:

namelist([ {‘name‘: ‘Bart‘}, {‘name‘: ‘Lisa‘}, {‘name‘: ‘Maggie‘} ])
# returns ‘Bart, Lisa & Maggie‘

namelist([ {‘name‘: ‘Bart‘}, {‘name‘: ‘Lisa‘} ])
# returns ‘Bart & Lisa‘

namelist([ {‘name‘: ‘Bart‘} ])
# returns ‘Bart‘

namelist([])
# returns ‘‘

解决方案:

def namelist(names):
    str = ""
    if len(names) == 0:
        pass
    elif len(names) == 1:
        str = str + (names[0][name])
    else:
        for each in names[0:-2]:
            str = str + (each[name]) + (, )
        str = str + (names[-2][name]) + ( & ) + (names[-1][name])
    return str

codewars上的解决方案:from ezetter

def namelist(names):
    if len(names)==0: return ‘‘
    if len(names)==1: return names[0][name]
    return , .join([n[name] for n in names[:-1]]) +  &  + names[-1][name]

 

参考资料

http://www.linuxidc.com/Linux/2011-09/42950.htm

以上是关于[codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.的主要内容,如果未能解决你的问题,请参考以下文章

codewar

python str.format知识点备忘

python的str.format方法

python的str.format方法

#python str.format 方法被用于字符串的格式化输出。

Python——format()/str.format()函数