Python: Comma Code

论坛 期权论坛 脚本     
匿名技术用户   2021-1-3 15:49   21   0

学习《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))

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP