python实践项目二:列表转字符串

将列表各元素转换为字符串并以规定形式返回。

假定有下面这样的列表:spam = ['apples', 'bananas', 'tofu', 'cats'],将其转换成字符串:'apples, bananas, tofu and cats'。

该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入and,需注意的是倒数第二个列表项后面无需添加逗号和空格。
示例一:从键盘输入获取列表
 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 
 4 #获取列表
 5 inputlist=[]
 6 def getList():
 7     '从键盘输入获取列表'
 8     while 1:
 9         s = raw_input("请输入列表元素,输入空字符再按回车时结束:\n")
10         if s=='':
11             break
12         else:
13             inputlist.append(s)
14     return inputlist
15 # print getList()
16 #列表转string
17 def listToStr():
18     s=''
19     list0=getList()
20     listLen=len(list0)
21     if listLen==0:
22         return "你输入的是空列表,程序结束!"
23     elif listLen==1:
24         return str(list0)
25     else:
26         for i in range(listLen-2):
27             s+=str(list0[i])+', '
28         s+=str(list0[-2])+' and '+str(list0[-1])
29     return s
30 #调用函数
31 print listToStr()

 运行结果:

 示例二:函数调用时写入列表

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 def listToString(list0):
 4     length=len(list0)
 5     if length==0:
 6         print "空列表,不打印任何内容。"
 7     elif length==1:
 8         print str(list0[0])
 9     else:
10         str0 = ''
11         for i in range(len(list0)-2):
12             str0=str0+str(list0[i])+' , '
13         str0=str0+str(list0[-2])+' and '+str(list0[-1])
14         print str0
15 listToString(['apples', 'bananas', 'tofu', 'cats'])

运行结果:

哪怕是咸鱼,也要做最咸的那条
原文地址:https://www.cnblogs.com/heyangblog/p/10995454.html