Python: Comma Code

本文介绍了一种将列表转换为带有特定格式的字符串的方法。通过定义函数list2Str,可以将列表项用逗号隔开,并在最后一项前插入'and'。提供了两种实现方式:一种是通过循环逐个拼接字符串;另一种则是利用Python内置函数join来简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值