###初学Python,希望能和大家多多交流,所上传代码为自己编写手打,请勿用于其他用途,谢谢!
**Python3实践项目:逗号代码
假定有下面这样的列表:
spam=[‘apples’,‘bananas’,‘tofu’,’ cats’]
编写一个函数,它以一个列表值作为参数,返回一个字符串。该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入 and 。例如,将前面的spam列表传递给函数,将返回’apples,bananas,tofu,and cats’。但是你的函数应该能够传递给它的任何列表。
代码如下:
def function_1(spam):
out1 = ''
spam1 = spam[:len(spam)-1] + ['and'] + [spam[len(spam)-1]]
for i in range(len(spam1)-2):
out = spam1[i]
out1 += out + ', '
#print(out1)
out2 = spam1[len(spam1)-1]
#print(out2)
out3 = out1 + 'and '+ out2
#print(spam1)
print(out3)
spam = ['apples','bananas','tofu','cats']
#spam = ['dogs','cats','pigs','tiggers','fish']
function_1(spam)
Ps:表项之间以逗号和空格分隔,要有逗号,还要有空格!
希望大家提出宝贵建议和改进策略,谢谢!
结果如下:
G:\Python\Python37-32\python.exe G:/Python/Example/Example_4_Exam_1.py
apples, bananas, tofu, and cats