英文:
Line-by-Line Lists - Python
问题
我正在尝试为我的“终端”用户提供一个选择列表,以便他们可以选择要执行的操作。但是当我运行我的程序时,它也包括了方括号。它仍然正常运行,但看起来有点奇怪:
user_want_to_do = ["Open Google", "Access Files", "Exit Terminal"]
print("\n")
print(user_want_to_do)
opt = input("请从上面的列表中输入您想要执行的操作:")
有什么建议吗?
英文:
I'm trying to give the user of my "Terminal" a list from which they can choose what to do. But when I run my program, it includes the brackets as well. It still runs as normal, but it just looks a bit funny:
user_want_to_do = ["Open Google", "Access Files", "Exit Terminal"]
print("\n")
print(user_want_to_do)
opt = input("Please input what you want to do from the list above:")
Any Suggestions?
答案1
得分: 3
你可以通过将它们连接成字符串来打印它们
``` " ".join(user_want_to_do) ```
一个“更漂亮”的解决方案 -
user_want_to_do = ["打开Google", "访问文件", "退出终端"]
for i, item in enumerate(user_want_to_do, start=1):
print(f"{i}. {item}")
将列表打印为带编号的列表
英文:
You can just print them as strings by joining them
" ".join(user_want_to_do)
A "prettier" solution -
user_want_to_do = ["Open Google", "Access Files", "Exit Terminal"]
for i, item in enumerate(user_want_to_do, start=1):
print(f"{i}. {item}")
Prints the list as a numbered list
答案2
得分: 1
以下是翻译好的部分:
你可以使用解包操作来打印时去掉括号:
user_want_to_do = ["Open Google", "Access Files", "Exit Terminal"]
print(*user_want_to_do, sep=", ") # 同时去掉引号
输出:
Open Google, Access Files, Exit Terminal
如果你想要它们分别显示在不同行:
```python
print(*user_want_to_do, sep="\n")
输出:
Open Google
Access Files
Exit Terminal
如果你想要保留引号,你可以将字符串映射到 repr
函数:
print(*map(repr, user_want_to_do), sep=", ")
输出:
'Open Google', 'Access Files', 'Exit Terminal'
或者从列表的表示中去掉括号:
print(repr(user_want_to_do).strip('[]'))
输出:
'Open Google', 'Access Files', 'Exit Terminal'
英文:
You can print without the brackets with unpacking:
user_want_to_do = ["Open Google", "Access Files", "Exit Terminal"]
print(*user_want_to_do, sep=", ") # removes quotes as well
output:
Open Google, Access Files, Exit Terminal
If you want them on separate lines instead:
print(*user_want_to_do, sep="\n")
output:
Open Google
Access Files
Exit Terminal
If you want to keep the quotes you can map the strings to the repr
function:
print(*map(repr,user_want_to_do), sep=", ")
output:
'Open Google', 'Access Files', 'Exit Terminal'
or strip brackets from the list's representation:
print(repr(user_want_to_do).strip('[]'))
output:
'Open Google', 'Access Files', 'Exit Terminal'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论