Python解包列表以在格式化字符串中使用

huangapple go评论87阅读模式
英文:

Python unpack list for use in formatted string

问题

我有一个字符串,根据用户输入动态创建。我在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

列表的长度是可变的,所以我不能逐个插入列表元素。

英文:

I have a string that I am dynamically creating based off user input. I am using the .format function in Python to add a list into the string, but I would like to remove the quotes and brackets when printing.

I have tried: <br>

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

and

return return ((&#39;{} is {}x effective against {}&#39;).format(opponentType, overallHitMultiplier, playerTypes))

which both return a string that looks like this:

fighting is 2x effective against [&#39;normal&#39;, &#39;ghost&#39;]

but I would like it to return something like:

fighting is 2x effective against normal, ghost

The length of the list is variable so I can't just insert the list elements one by one.

答案1

得分: 2

以下是翻译好的内容:

这是一个更完整的响应

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' 和 {player_types[-1]}'

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

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

>>> convert_player_types_to_str(['normal', 'ghost', 'goblin'])
'normal, ghost 和 goblin'
英文:

Here is a more complete response:

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

&gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;])
&#39;normal&#39;

&gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;, &#39;ghost&#39;])
&#39;normal and ghost&#39;

&gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;, &#39;ghost&#39;, &#39;goblin&#39;])
&#39;normal, ghost and goblin&#39;

huangapple
  • 本文由 发表于 2020年1月7日 02:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定