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

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

Python unpack list for use in formatted string

问题

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

我尝试过:

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

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

这两者都返回一个字符串,看起来像这样:

  1. fighting is 2x effective against [normal, ghost]

但我想要的是返回类似这样的内容:

  1. 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>

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

and

  1. 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

以下是翻译好的内容:

  1. 这是一个更完整的响应
  2. def convert_player_types_to_str(player_types):
  3. n = len(player_types)
  4. if not n:
  5. return ''
  6. if n == 1:
  7. return player_types[0]
  8. return ', '.join(player_types[:-1]) + f' 和 {player_types[-1]}'
  9. >>> convert_player_types_to_str(['normal'])
  10. 'normal'
  11. >>> convert_player_types_to_str(['normal', 'ghost'])
  12. 'normal 和 ghost'
  13. >>> convert_player_types_to_str(['normal', 'ghost', 'goblin'])
  14. 'normal, ghost 和 goblin'
英文:

Here is a more complete response:

  1. def convert_player_types_to_str(player_types):
  2. n = len(player_types)
  3. if not n:
  4. return &#39;&#39;
  5. if n == 1:
  6. return player_types[0]
  7. return &#39;, &#39;.join(player_types[:-1]) + f&#39; and {player_types[-1]}&#39;
  8. &gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;])
  9. &#39;normal&#39;
  10. &gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;, &#39;ghost&#39;])
  11. &#39;normal and ghost&#39;
  12. &gt;&gt;&gt; convert_player_types_to_str([&#39;normal&#39;, &#39;ghost&#39;, &#39;goblin&#39;])
  13. &#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:

确定