用于格式化字符串的Python解包列表

2024-05-19 02:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基于用户输入动态创建的字符串。我正在使用Python中的.format函数将列表添加到字符串中,但我希望在打印时删除引号和方括号

我试过:

return (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, [str(x) for x in playerTypes]))

return return (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, playerTypes))

两者都返回如下所示的字符串:

fighting is 2x effective against ['normal', 'ghost']

但我希望它能返回如下内容:

fighting is 2x effective against normal, ghost

列表的长度是可变的,所以我不能一个接一个地插入列表元素


Tags: 字符串用户format列表returnis动态创建ghost
1条回答
网友
1楼 · 发布于 2024-05-19 02:24:25

以下是一个更完整的回答:

def convert_player_types_to_str(player_types):
    n = len(player_types)
    if not n:
        return ''
    if n == 1:
        return player_types[0]
    return ', '.join(player_types[:-1]) + f' and {player_types[-1]}'

>>> convert_player_types_to_str(['normal'])
'normal'

>>> convert_player_types_to_str(['normal', 'ghost'])
'normal and ghost'

>>> convert_player_types_to_str(['normal', 'ghost', 'goblin'])
'normal, ghost and goblin'

相关问题 更多 >

    热门问题