|
学习《Python编程快速上手》P79 问题链接:https://automatetheboringstuff.com/chapter4/ Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats'] Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. 代码实现(1): # Problem: Comma Code
# The url of the problem: https://automatetheboringstuff.com/chapter4/
# Define the function
def list2Str(List):
Str = ''
for i in range(len(List)-1):
Str += List[i] + ', '
Str += ('and ' + List[-1])
return Str
# Enter a list
spam = ['apples','bananas','tofu','cats']
# Show the result
print(list2Str(spam))
代码实现(2): # Problem: Comma Code
# The url of the problem: https://automatetheboringstuff.com/chapter4/
# Define the function
def list2Str(List):
List[-1] = 'and ' + List[-1]
return ', '.join(List)
# Enter a list
spam = ['apples','bananas','tofu','cats']
# Show the result
print(list2Str(spam))
|