【python实践项目】实践1,逗号代码

逗号代码:

题目:

  假定有下面这样的有列表:spam = {‘apples’,‘bananas’,‘tofu’,‘cats’}

  编写一个函数,它以一个列表值作为参数,返回一个字符串;该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个 表项之前插入 and;

例如:

  将前面的spam列表传递给函数,将返回‘apples, bananas, tofu, and cats’。但你的函数应该能够处理传递给它的任何列表。

思路:

  编写函数test,用for循环遍历至列表的倒数第二个表项,最后加入and与最后一个表项。

代码:

 1 """
 2 需求:
 3 1、一个函数
 4 2、参数是一个列表值
 5 3、返回一个字符串
 6     该字符串包含所有表项,表项之间以逗号和空格分割,并在最后一个表项之前插入 and
 7 """
 8 
 9 def test(spam):
10     _str = ''
11     for i in range(len(spam)-1):
12         _str = _str + spam[i] + ', '
13     _str = _str + 'and '
14     _str = _str + spam[len(spam)-1] + ''
15     return _str
16 
17 listtests1 = ['apples', 'bananas', 'tofu', 'cats']
18 print(test(listtests1))

 

posted @ 2022-03-27 16:25  biao666  阅读(211)  评论(0)    收藏  举报