【发布时间】:2026-01-07 21:25:05
【问题描述】:
每个人。我正在尝试解决如下编码挑战:
- 从用户那里得到一个字符串。之后,询问用户“你想对字符串做什么?”,允许用户选择下一个功能: "upper" - 使所有字符串大写 "lower" - 使所有字符串小写 " "spaces2newline" - 将所有空格重新换行 ... 打印结果 *使用字典“包装”该菜单
所以,我从中得到的是我需要制作一个字典,我可以从中调用命令并将它们分配给字符串。
显然,这是行不通的:
commands = {"1" : .upper(), "2" : .lower(), "3" : .replace(" ",\n)}
user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)\n
\t1. Make all characters capital\n
\t2. Make all characters lowercase")
#other options as input 3, 4, etc...
但也许有人可以推荐一种方法来实现这个想法?
我的主要问题是:
- 您能否以某种方式将内置函数分配给变量、列表或字典?
- 如何从字典中调用这样的函数并将它们作为命令添加到字符串的末尾?
感谢您的帮助!
【问题讨论】:
-
天真的方式类似于
{"1": lambda x: x.upper(), "2": lambda x: x.lower(), "3": lambda x: x.replace(" ", "\n")}
标签: python dictionary built-in