将列表各元素转换为字符串并以规定形式返回。
假定有下面这样的列表: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()
显示结果: