提问人:boludoz 提问时间:11/9/2023 最后编辑:boludoz 更新时间:11/9/2023 访问量:77
Python 匹配大小写:无论字母是否大写,我如何匹配大小写?
Python Match Case: How can I match a case no matter if the letters are capitalized or not easily?
问:
我有下一个代码(在 Python 中):
lang = input("What's the programming language you want to learn? ").upper()
match lang:
case "JavaScript".upper():
print("You can become a web developer.")
case "Python".upper():
print("You can become a Data Scientist")
case "PHP".upper():
print("You can become a backend developer")
case "Solidity".upper():
print("You can become a Blockchain developer")
case "Java".upper():
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is solving problems.")
我只是在玩它,我发现它非常有用,但是当我运行它时,我收到以下错误:
[Running] python -u "...\match.py"
File "...\match.py", line 4
case "JavaScript".upper():
^
SyntaxError: invalid syntax
这是一个错误,还是我如何以这种方式将条件转换为大写,而不必编写非常大的代码?
我阅读了文档,可以做很多事情,但我没有找到解决方案,或者我不知道如何查看它。
编辑:
根据 @Karl Knechtel 的意见,静态情况的可能解决方案如下:
lang = input("What's the programming language you want to learn? ").upper()
match lang:
case "JAVASCRIPT":
print("You can become a web developer.")
case "PYTHON":
print("You can become a Data Scientist")
case "PHP":
print("You can become a backend developer")
case "SOLIDITY":
print("You can become a Blockchain developer")
case "JAVA":
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is solving problems.")
答:
0赞
sbottingota
11/9/2023
#1
问题是 python 无法像您尝试的那样计算大小写位中的表达式。你可以把它们都写成大写字母,从下面开始:
lang = input("What's the programming language you want to learn? ").upper()
match lang:
case "JAVASCRIPT":
print("You can become a web developer.")
case "PYTHON":
print("You can become a Data Scientist")
case "PHP":
print("You can become a backend developer")
case "SOLIDITY":
print("You can become a Blockchain developer")
case "JAVA":
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is solving problems.")
或者,你可以只使用 if 语句:
lang = input("What's the programming language you want to learn? ").upper()
if lang == "JavaScript".upper():
print("You can become a web developer.")
elif lang == "Python".upper():
print("You can become a Data Scientist")
elif lang == "PHP".upper():
print("You can become a backend developer")
elif lang == "Solidity".upper():
print("You can become a Blockchain developer")
elif lang == "Java".upper():
print("You can become a mobile app developer")
else:
print("The language doesn't matter, what matters is solving problems.")
注意您可能还希望删除 中的前导/尾随空格或标点符号。这是一种方法。lang
import string
lang = input("What's the programming language you want to learn? ")
lang = lang.upper().strip().strip(string.punctuation)
评论
case "JAVASCRIPT":
if
elif
else
match... case...
switch
if... elif... else
case
match
case x if x == "Javascript".upper():
if-else