Line-by-Line Lists – Python

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

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'

huangapple
  • 本文由 发表于 2023年7月10日 18:14:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652756.html
匿名

发表评论

匿名网友

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

确定