英文:
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 (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, [str(x) for x in playerTypes]))
and
return return (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, playerTypes))
which both return a string that looks like this:
fighting is 2x effective against ['normal', 'ghost']
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 ''
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论