1

如标题所述,我定义了一个字符串列表变量,我需要将列表的内容打印为输入行的一部分,其中还包括其他文本,我需要将列表的内容打印到带有正方形的屏幕括号但没有撇号。

这是我的代码:

interactive_options = ['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
user_choice = input(f'''
Please enter a choice \n{interactive_options}
''')

当前输出为:

请输入一个选项

['列表','英雄','反派','搜索','重置','添加','删除','高','战斗','健康','退出']

...而我需要:

请输入一个选项

[列表,英雄,反派,搜索,重置,添加,删除,高,战斗,健康,退出]:

注意 - 我还需要在列表内容的末尾打印一个冒号,但也不能让它工作。

4

2 回答 2

1

如果您正在使用print(interactive_options)- 您会得到以下结果str(interactive_options)

>>> print(interactive_options)
['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
>>> str(interactive_options)
['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']

但是,您可以使用join(通过连接可迭代(列表、字符串、元组)的所有元素,由字符串分隔符分隔)来根据需要格式化输出,如下所示:

>>> ", ".join(interactive_options)
list, heroes, villains, search, reset, add, remove, high, battle, health, quit

您可以在输出中添加括号和冒号:

>>> interactive_options_print = ", ".join(interactive_options)
>>> interactive_options_print = "[" + interactive_options_print + "]:"
>>> interactive_options_print
[list, heroes, villains, search, reset, add, remove, high, battle, health, quit]:
于 2022-02-15T22:45:04.193 回答
-1

你可以试试这个——

interactive_options = ['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
user_choice = input(f'''
Please enter a choice \n{str(interactive_options).replace("'","")}:
''')
于 2022-02-15T22:46:01.997 回答